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 become dark theme, more pro and high-tech. Show code.
To modify the classification plot to a dark theme that looks more professional and high-tech, you can make use of Matplotlib's style settings to change the plot appearance. Here, I will show you how to apply a dark theme for the classification plot in the predict_image function:
Before you make the plot, set the plot style to a dark theme using plt.style.use('dark_background'). This will ensure that all elements of the plot, including the background, text, and lines, are appropriately styled for a dark theme. You can revert back to the default style or choose a different style for other plots if needed.
Here's an updated version of the relevant part of your predict_image function to include these changes:
from matplotlib import pyplot as plt
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)
# Switch to dark theme
plt.style.use('dark_background')
# 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}')
for i, v in enumerate(class_probabilities):
axs[2].text(i, v + 0.02, f"{v:.2f}", color='white', ha='center')
plt.tight_layout()
plt.show()
# Revert to default style after plotting if needed for other plots
plt.style.use('default')
In this code snippet, plt.style.use('dark_background') applies a dark theme to all subsequent plots. This change affects the background color, text color, and major elements of the plot to ensure they are clearly visible against a dark background. By setting the style before plotting and reverting it back to default after plotting, you can apply the dark theme specifically to the classification output plot without affecting other plots that might be generated elsewhere in your code or in other cells when using Jupyter Notebooks.
To add a white bounding box around the segmentation mask output to make it stand out against the dark background, you can compute the bounding box coordinates based on the segmentation mask and draw it using Matplotlib's rectangle drawing function. This involves finding the extremes (min and max) of the non-zero pixels in the segmentation mask and then drawing a rectangle from those points.
Here's how you can modify the predict_image function to include drawing a white bounding box around the segmentation 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)
# Switch to dark theme
plt.style.use('dark_background')
# 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')
seg_img = seg_output[0, :, :, 0]
# Find non-zero mask points
non_zero_coords = np.nonzero(seg_img)
if non_zero_coords[0].size > 0:
y1, x1 = np.min(non_zero_coords, axis=1)
y2, x2 = np.max(non_zero_coords, axis=1)
# Draw white rectangle
rect = plt.Rectangle((x1, y1), x2-x1, y2-y1, edgecolor='white', facecolor='none')
axs[1].add_patch(rect)
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}')
for i, v in enumerate(class_probabilities):
axs[2].text(i, v + 0.02, f"{v:.2f}", color='white', ha='center')
plt.tight_layout()
plt.show()
# Revert to default style after plotting if needed for other plots
plt.style.use('default')
In this updated version of the predict_image function, after displaying the segmentation output, the function calculates the coordinates of a bounding box that encompasses all non-zero pixels of the segmentation mask. It then uses plt.Rectangle to create a rectangle from these coordinates, which is then added to the axis that displays the segmentation output. The rectangle is set with edgecolor='white' and facecolor='none' to ensure it appears as a white outline around the segmented area.