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. Check these functions:"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)"
Because I cannot get the correct predicted classification output, check error.
Based on the description and the code you've provided, if you're having issues with getting correct predicted classification outputs, there are several aspects you might want to examine to troubleshoot and resolve the problem:
1. Model Accuracy and Training:
Model Accuracy: Ensure that the model has been trained with a high accuracy on the training dataset. Low accuracy could mean the model hasn't learned to classify images correctly.
Overfitting: Make sure your model isn't overfitting on the training data, which would make it perform poorly on new, unseen images.
Data Augmentation: Verify if data augmentation techniques were used correctly during training to introduce variability into the training process.
Training Data Quality: Assess the quality and variability of the training data. The model will perform poorly on unseen images if the training data doesn't represent the real-world distribution or if it's noisy.
2. Preprocessing Consistency:
Ensure that the image preprocessing steps during inference (prediction time) match exactly with those used during training. This includes resizing, normalization, and color conversion steps.
3. Model Loading:
Ensure the correct model weights are being loaded. Sometimes, incorrect file paths or issues during the model saving or loading process might lead to using an uninitialized or a different model than intended.
4. Bug in the Code:
Model Prediction Line: Double-check the model prediction logic to make sure the model is being called correctly, and the outputs are handled correctly.
# This line gets both class and segmentation outputs. Make sure it's executed correctly.
class_output, seg_output = model.predict(img_expanded)
5. Debugging Steps:
Test with Training Images: Try predicting on images that were part of the training or validation set to see if the model can accurately classify or segment those. If it can, the issue might be with how new images are preprocessed or fundamentally different from your training data.
Inspect Model Outputs: Analyze the raw output scores (class_output variable) from the model to see if the model is uncertain or if there's an issue with the way the highest probability class is selected.
Output Shape: Verify that the output shape corresponds to what you expect (num_classes for classification output).
Debugging Code:
Add print statements to debug and understand the output at each step, especially before and after predictions.
print("Shape of input image:", img_expanded.shape)
print("Prediction output:", class_output)
6. Correct Image Size and Channels:
Make sure the value of image_size used during prediction matches the one used during training. The number of channels (RGB vs. Grayscale) must also match.
After going through these checks, if the problem persists, it might be helpful to:
Revisit the model architecture and training process for potential issues.
Consider evaluating the model's performance with different hyperparameters or optimization techniques if you suspect the model hasn't generalized well.