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.
The code you provided is detailed and attempts to perform both classification and segmentation tasks on uploaded images using a pre-trained model. If you are encountering issues getting the correct predicted classification output, here are a few potential areas to investigate and possible solutions:
Model Loading:
Ensure that the model at saved_model_path is correctly loaded. Issues can arise if the model file is corrupted, not completely saved, or if there has been a change in the environment (e.g., TensorFlow versions) since the model was saved. Verify the environment is consistent, especially the TensorFlow version.
Input Preprocessing:
Double-check the preprocessing steps applied to the input image before prediction. The preprocessing should be identical to what was done during training, including resizing, normalization, or color space conversion. Mismatches here can lead to poor model performance.
Model Output:
Confirm that class_output is being correctly interpreted. The np.argmax(class_output) function returns the index of the class with the highest probability, which should correspond to your labels. Make sure the labels list is in the same order as during training.
Custom Object: segmentation_loss:
When loading the model, ensure that all custom objects used during model training, such as segmentation_loss, are available. It seems you've done this with custom_objects, but it's good to confirm that all custom metrics, layers, or other functionalities are correctly defined and passed.
Version Compatibility:
If you trained the model in a different TensorFlow version than you're using for inference, there might be compatibility issues. Ensure that the TensorFlow version matches or is compatible.
Debugging Model Prediction:
To further debug, try simplifying the code to predict on a single, well-understood image where you know the expected outputs. This can help establish whether the issue lies in model inference or the subsequent data handling and visualization code.
Model Evaluation and Sanity Check:
As a sanity check, evaluate the model directly on your training or validation set where you expect high accuracy, to confirm that the model itself is performing as expected. This can help isolate if the issue is with how new images are processed or with the model's state.
Verbose Output for Debugging:
Add verbose output to your prediction step to check the raw probabilities being output by the model. This can sometimes give clues as to whether the issue is with the data, the model, or the interpretation of the output.
If after checking these points the issue remains, consider providing specific error messages or behaviors you are encountering for more targeted advice.