out = Output()
def predict_image(image_path):
# Load and preprocess the image
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
img_resized = cv2.resize(img, (image_size, image_size))
img_expanded = np.expand_dims(img_resized, axis=0)
# Predict using the model
class_output, seg_output = model.predict(img_expanded)
# Get the predicted class
predicted_class_index = np.argmax(class_output)
predicted_class = labels[predicted_class_index]
# Clear the previous output
with out:
clear_output(wait=True)
# Visualize the input and segmentation output
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
axs[0].imshow(img)
axs[0].set_title("Input Image")
axs[0].axis("off")
axs[1].imshow(seg_output[0, :, :, 0], cmap='gray')
axs[1].set_title("Segmentation Output")
axs[1].axis("off")
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
axs[2].bar(x_pos, class_probabilities, align='center', alpha=0.7, color='blue')
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right")
axs[2].set_ylabel('Probability')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}') # Increased title font size
for i, v in enumerate(class_probabilities):
axs[2].text(i, v + 0.02, f"{v:.2f}", color='black', ha='center')
plt.tight_layout()
plt.show()
Define a callback function to handle the uploaded file
def on_upload(change):
# Get the uploaded file
uploaded_filename = next(iter(uploader.value))
uploaded_file = uploader.value[uploaded_filename]
# Save the uploaded file
with open(uploaded_filename, 'wb') as f:
f.write(uploaded_file['content'])
# Predict and visualize the image
predict_image(uploaded_filename)
Define a function to handle the button click event and clear the output
"
The above is the Python code with Keras to do inference using the multi-task learning model, this model will take the image as input and provide one classification output and one segmentation output, this code let user to select one image and performance inference. Help me to make the classification plot look more high future tech, more advanced, more professional.
Enhancing the classification plot in your provided code involves improving the aesthetics and making it more informative for a "future tech" look. Here's an updated approach focused on the predict_image function where the classification plot is generated. Changes include:
Using a more sophisticated plotting library/component than the basic matplotlib bar plot, such as seaborn, for a sleeker look.
Adding more detailed visual elements, such as gradient color in bars, enhancing text readability, and employing a more modern color palette.
Including additional insightful metrics or annotations directly on the plot.
Let's focus on the section of your predict_image function that deals with visualization, specifically the classification plot. I'll integrate the aforementioned enhancements:
from matplotlib import cm # For colormap functionalities
# Within your predict_image function, update the plotting part accordingly:
# Assuming this section updates the classification plot in your current `predict_image` function
axs[2].cla() # Clear the previous plot to ensure a fresh start
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
# Use seaborn for a more sophisticated barplot
sns.barplot(x=x_pos, y=class_probabilities, palette='viridis', ax=axs[2])
# Customizing the plot for a more "futuristic" look
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right", fontweight='light', fontsize='x-small')
axs[2].set_ylabel('Probability', fontsize='small', fontweight='bold')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}', fontsize='medium', fontweight='bold')
axs[2].grid(True, which='major', linestyle='--', linewidth='0.5', color='grey')
# Adding a color gradient to bars based on their height/value
bar_colors = cm.viridis(class_probabilities / np.max(class_probabilities))
for bar, color in zip(axs[2].patches, bar_colors):
bar.set_color(color)
# Annotating bars with the probability values
for i, v in enumerate(class_probabilities):
axs[2].text(i, v + 0.02, f"{v:.2f}", color='black', ha='center', fontsize='x-small')
plt.tight_layout()
plt.show()
Explanation:
Seaborn for Barplot: Using seaborn enhances the visual quality of the plot. The viridis palette is chosen for a modern, tech-savvy look, but you can explore other palettes like plasma, inferno, etc., for different effects.
Customizing Appearance: Adjustments to font sizes, weights, and adding a grid improve readability and visual appeal.
Gradient Bar Colors: Implementing a gradient color scheme on the bars based on their value adds a dynamic and modern aesthetic to the plot.
Annotations for Clarity: Including precise value annotations on each bar aids in readability and delivers exact information at a glance.
Remember, achieving a "high future tech" look is as much about the clarity and presentation of data as it is about aesthetic tweaks. Consider your audience's needs and adjust the complexity, color scheme, and information density accordingly.
Certainly! Below is the revised full code of the predict_image function, incorporating the enhancements suggested for a more future-tech and professional appearance of the classification plot using the seaborn library and custom visual enhancements.
Make sure you have seaborn installed in your environment (!pip install seaborn if necessary).
import numpy as np
import cv2
from matplotlib import pyplot as plt
import seaborn as sns
from matplotlib import cm # For colormap functionalities
from IPython.display import clear_output
# Assuming 'labels' is a predefined list of class names
# labels = ["bridge", "excess", "good", "insuff", "no"]
# Assuming 'model' is your loaded or defined model ready for prediction
# model = your_model_loading_or_creation_function()
def predict_image(image_path, model, image_size=224, labels=["bridge", "excess", "good", "insuff", "no"]):
# Load and preprocess the image
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
img_resized = cv2.resize(img, (image_size, image_size))
img_expanded = np.expand_dims(img_resized, axis=0)
# Predict using the model
class_output, seg_output = model.predict(img_expanded)
# Get the predicted class
predicted_class_index = np.argmax(class_output)
predicted_class = labels[predicted_class_index]
# Clear the previous output
clear_output(wait=True)
# Visualize the input and segmentation output
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
axs[0].imshow(img)
axs[0].set_title("Input Image")
axs[0].axis("off")
axs[1].imshow(seg_output[0, :, :, 0], cmap='gray')
axs[1].set_title("Segmentation Output")
axs[1].axis("off")
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
# Use seaborn for a more sophisticated barplot
sns.barplot(x=x_pos, y=class_probabilities, palette='viridis', ax=axs[2])
# Customizing the plot for a more "futuristic" look
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right", fontweight='light', fontsize='x-small')
axs[2].set_ylabel('Probability', fontsize='small', fontweight='bold')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}', fontsize='medium', fontweight='bold')
axs[2].grid(True, which='major', linestyle='--', linewidth='0.5', color='grey')
# Adding a color gradient to bars based on their height/value
bar_colors = cm.viridis(class_probabilities / np.max(class_probabilities))
for bar, color in zip(axs[2].patches, bar_colors):
bar.set_color(color)
# Annotating bars with the probability values
for i, v in enumerate(class_probabilities):
axs[2].text(i, v + 0.02, f"{v:.2f}", color='black', ha='center', fontsize='x-small')
plt.tight_layout()
plt.show()
# Usage example:
# predict_image("path/to/your/image.jpg", model, image_size=224, labels=["bridge", "excess", "good", "insuff", "no"])
In this comprehensive version of the predict_image function:
The image is loaded, preprocessed to the expected input size, and then fed into the model for prediction.
The output probabilities for the classification task are visualized in a bar plot with a futuristic look and feel, employing seaborn's barplot for aesthetic enhancement.
Segmentation output is displayed alongside the input image and classification probabilities to provide a comprehensive insight into the model's prediction for both tasks.
This version aims to balance the aesthetic appeal with functionality, offering a more professional presentation of the model's predictions.