bg_color = '#303030' # Lighter than black, as per the previous specification
text_color = 'white'
for i in range(num_images):
plt.figure(figsize=(10, 5))
plt.subplot(2, 3, 1)
plt.imshow(selected_images[i])
plt.title(f"Input Image\nGround Truth Label: {labels[np.argmax(selected_labels[i])]}\nPredicted Label: {labels[predicted_classes[i]]}", color=text_color)
plt.axis("off")
plt.gcf().set_facecolor(bg_color)
plt.subplot(2, 3, 2)
plt.imshow(selected_masks[i].squeeze(), cmap="gray")
plt.title("Ground Truth Segmentation Mask", color=text_color)
plt.axis("off")
plt.subplot(2, 3, 3)
plt.imshow(predicted_masks[i].squeeze(), cmap="gray")
plt.title("Predicted Segmentation Mask", color=text_color)
plt.axis("off")
plt.tight_layout()
plt.show()
preprocess and predict on the selected image
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()
'''
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)
# Configure specific style options for lighter background
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
# Lighten background
bg_color = '#303030' # Lighter than black for contrast
fig.patch.set_facecolor(bg_color)
for ax in axs:
ax.set_facecolor(bg_color)
# Set spines color to lighter tone
ax.spines['bottom'].set_color('grey')
ax.spines['top'].set_color('grey')
ax.spines['right'].set_color('grey')
ax.spines['left'].set_color('grey')
ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')
axs[0].imshow(img)
axs[0].set_title("Input Image", color='white', fontweight='bold')
axs[0].axis("off")
axs[1].imshow(seg_output[0, :, :, 0], cmap='gray')
axs[1].set_title("Segmentation Output", color='white', fontweight='bold')
axs[1].axis("off")
# Adjusted plot for classification
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
bars = axs[2].bar(x_pos, class_probabilities, align='center', alpha=0.7, color='cyan')
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right", color='white')
axs[2].set_ylabel('Probability', color='white')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}', color='white', fontweight='bold')
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()
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
print("Number of train images:", len(X_train))
print("Number of train binary masks:", len(y_train_seg))
print("Number of validation images:", len(X_val))
print("Number of validation binary masks:", len(y_val_seg))
print("Number of test images:", len(X_test))
print("Number of test binary masks:", len(y_test_seg))
input_shape = (image_size, image_size, 3)
num_classes = len(labels)
saved_model_path = "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/model/pcbmtl_bdip.h5"
custom_objects = {"segmentation_loss": segmentation_loss}
Load model
model = load_model(saved_model_path, custom_objects=custom_objects)
Test model
test_model(model, X_test, y_test_class, y_test_seg, labels, num_images=5)
uploader = widgets.FileUpload(accept='image/*', multiple=False)
uploader.observe(on_upload, names='value')
buttons_layout = HBox([uploader, clear_button])
display(buttons_layout)
display(out)
"
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, however the predicted output always produce the wrong classification output. Check and correct these functions to solve the problem:"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)
# Configure specific style options for lighter background
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
# Lighten background
bg_color = '#303030' # Lighter than black for contrast
fig.patch.set_facecolor(bg_color)
for ax in axs:
ax.set_facecolor(bg_color)
# Set spines color to lighter tone
ax.spines['bottom'].set_color('grey')
ax.spines['top'].set_color('grey')
ax.spines['right'].set_color('grey')
ax.spines['left'].set_color('grey')
ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')
axs[0].imshow(img)
axs[0].set_title("Input Image", color='white', fontweight='bold')
axs[0].axis("off")
axs[1].imshow(seg_output[0, :, :, 0], cmap='gray')
axs[1].set_title("Segmentation Output", color='white', fontweight='bold')
axs[1].axis("off")
# Adjusted plot for classification
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
bars = axs[2].bar(x_pos, class_probabilities, align='center', alpha=0.7, color='cyan')
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right", color='white')
axs[2].set_ylabel('Probability', color='white')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}', color='white', fontweight='bold')
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()
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
clear_button = Button(description='Clear')
def clear_output_button_clicked(button):
out.clear_output()
clear_button.on_click(clear_output_button_clicked)"
Also, this code work well :"import ipywidgets as widgets
from IPython.display import display, clear_output
from ipywidgets import Output
import matplotlib.pyplot as plt
import cv2
import numpy as np
Load the saved model
custom_objects = {"segmentation_loss": segmentation_loss}
model = load_model(saved_model_path, custom_objects=custom_objects)
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)
Attach the callback function to the file uploader
uploader.observe(on_upload, names='value')
Display the file uploader widget and the Output widget
display(uploader)
display(out)"
Show the fixed code.
From the detailed description you've provided, it seems you want to correct the predict_image function in the multi-task model to enhance classification and segmentation accuracy. First, ensure your model is properly trained and the data is adequately preprocessed for both classification and segmentation tasks.
Below is the corrected version of the predict_image function with an emphasis on ensuring that the image preprocessing steps match those used during training. One common issue in model predictions being off is a mismatch in preprocessing steps (e.g., normalization used during training but not in prediction).
I've corrected the predict_image function to ensure it follows best practices, and included comments to point out potential areas that might need adjustments based on how the model was trained (e.g., image preprocessing steps like normalization).
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
# Ensure the image is resized according to the input size expected by the model.
img_resized = cv2.resize(img, (image_size, image_size))
# Normalize the image if the model was trained with normalized images.
# Adjust the normalization parameters based on your model's training preprocessing steps.
# Example normalization (if your images were in the range [0,1] during training):
img_normalized = img_resized / 255.0
# Expand the dimensions to add the batch size
img_expanded = np.expand_dims(img_normalized, axis=0)
# Predict using the model
# Ensure the model expects a single input for both tasks.
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]
# Visualization setup
bg_color = '#303030'
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
fig.patch.set_facecolor(bg_color)
for ax in axs:
ax.set_facecolor(bg_color)
ax.spines['bottom'].set_color('grey')
ax.spines['top'].set_color('grey')
ax.spines['right'].set_color('grey')
ax.spines['left'].set_color('grey')
ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')
axs[0].imshow(img) # Original image, adjust if normalization display needed
axs[0].set_title("Input Image", color='white', fontweight='bold')
axs[0].axis("off")
axs[1].imshow(seg_output[0, :, :, 0], cmap='gray')
axs[1].set_title("Segmentation Output", color='white', fontweight='bold')
axs[1].axis("off")
# Adjusted plot for classification with correct color settings.
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
bars = axs[2].bar(x_pos, class_probabilities, align='center', alpha=0.7, color='cyan')
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right", color='white')
axs[2].set_ylabel('Probability', color='white')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}', color='white', fontweight='bold')
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()
Key adjustments:
Image normalization: If the model was trained on normalized images, ensure the same normalization is applied during prediction.
Image color conversion: Verification that the BGR to RGB conversion step matches your training data preprocessing is crucial if you are utilizing specific libraries (OpenCV loads images in BGR format by default, while models often expect RGB).
Visualization consistency: Ensure visualization styles (e.g., background color, axis labels) do not affect the interpretation of results. This change doesn't affect model performance but helps in consistent presentation.
If after making these adjustments, the predictions are still incorrect, consider revisiting your model's training process, the quality of your training data, and ensure the model architecture is suitable for the complexity of both tasks (classification and segmentation).