Count the number of images of each class in the train, validation, and test sets
train_counts = count_labels(y_train_class, label_encoder)
val_counts = count_labels(y_val_class, label_encoder)
test_counts = count_labels(y_test_class, label_encoder)
print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values()))
print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values()))
print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values()))
"
Add the code to print some random train images and train segmentation images with labels.
Certainly! There's a bit of code to add in order to display some random images from the training set along with their respective segmentation masks and labels. We will select a few random images and display them using matplotlib.
For simplicity, I'll show you how to randomly choose and display 3 images and their corresponding segmentation masks from the training dataset. Feel free to adjust the number of images by changing the num_images_to_show variable. Note that the labels have already been converted to categorical format for the training process; for display purposes, we will use the inverse transform method of label_encoder to get back the original labels.
Here is the code snippet you can add to your script:
import matplotlib.pyplot as plt
def display_random_images_with_masks(X_train, y_train_seg, y_train_class, label_encoder, num_images_to_show=3):
fig, axes = plt.subplots(num_images_to_show, 2, figsize=(10, num_images_to_show*3))
for i in range(num_images_to_show):
# Randomly select an image
index = random.randint(0, len(X_train) - 1)
# Convert the one-hot encoded class back to the original label
original_label = label_encoder.inverse_transform([np.argmax(y_train_class[index])])[0]
# Plot the original image
ax = axes[i, 0]
ax.imshow(cv2.cvtColor(X_train[index], cv2.COLOR_BGR2RGB))
ax.title.set_text(f'Original Image: {original_label}')
ax.axis('off')
# Plot the segmentation mask
ax = axes[i, 1]
ax.imshow(y_train_seg[index].reshape(image_size, image_size), cmap='gray')
ax.title.set_text('Segmentation Mask')
ax.axis('off')
plt.tight_layout()
plt.show()
# Call the function to display images and masks
display_random_images_with_masks(X_train, y_train_seg, y_train_class, label_encoder)
This function, display_random_images_with_masks, will plot a selected number of random images from your training dataset along with their corresponding segmentation masks. Each image is shown next to its mask for easy comparison. The title of each original image subplot includes the class label of the image, while the segmentation mask is shown in grayscale.
Remember to place this snippet at the appropriate location in your script, typically after the data has been loaded and processed but before the training begins. This ensures that the X_train, y_train_seg, y_train_class, and label_encoder variables are already available and properly initialized.
Printing all images and masks from a dataset, especially if it's large, could be impractical and time-consuming, and would likely overwhelm your interface or output console. Usually, datasets contain hundreds, if not thousands, of images, making it infeasible to display them all at once in most environments, such as Jupyter notebooks or Python scripts run in terminal windows.
However, if you have a specific small subset of your dataset or indeed have a very small dataset and you want to display every item, you could modify the function to iterate through the entire X_train array instead of selecting random images. Here's how you might do it, but proceed with caution due to the concerns mentioned above:
def display_all_images_with_masks(X_train, y_train_seg, y_train_class, label_encoder, rows_per_image=2):
total_images = len(X_train)
fig, axes = plt.subplots(total_images * rows_per_image, 2, figsize=(10, total_images * rows_per_image * 3))
for i in range(total_images):
# Convert the one-hot encoded class back to the original label
original_label = label_encoder.inverse_transform([np.argmax(y_train_class[i])])[0]
# Plot the original image
ax = axes[i * rows_per_image, 0]
ax.imshow(cv2.cvtColor(X_train[i], cv2.COLOR_BGR2RGB))
ax.title.set_text(f'Original Image: {original_label}')
ax.axis('off')
# Plot the segmentation mask
ax = axes[i * rows_per_image, 1]
ax.imshow(y_train_seg[i].reshape(image_size, image_size), cmap='gray')
ax.title.set_text('Segmentation Mask')
ax.axis('off')
# If you are showing masks next to every image, you might not need this
if rows_per_image > 1:
axes[i * rows_per_image + 1, 0].axis('off')
axes[i * rows_per_image + 1, 1].axis('off')
plt.tight_layout()
plt.show()
# Calling the function might look like this:
# display_all_images_with_masks(X_train, y_train_seg, y_train_class, label_encoder)
Important Notes:
Practicality: Before proceeding with displaying all images, consider whether it's practical and what you hope to achieve by doing so. For data exploration, randomly viewing a subset of images is often sufficient.
Performance: Generating a massive figure with all your images will be very heavy on memory and might crash your Python kernel, especially with large datasets.
Alternatives: Consider saving images to disk individually or creating a smaller, representative subset to visualize instead. Viewing or inspecting images in batches or using data augmentation techniques could also be instructive.
Modification Needed for Large Datasets: If you really need to inspect all images but have a large dataset, consider breaking down the task into smaller chunks, displaying a few images at a time, or utilizing a paginated display mechanism.
Remember, the solution provided is more theoretical for learning purposes, reflecting on what could be done rather than what should be done with large datasets.
ValueError: Image size of 1000x72000 pixels is too large. It must be less than 2^16 in each direction.
Error in callback <function _draw_all_if_interactive at 0x79fd6c50d000> (for post_execute):
ValueError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/matplotlib/pyplot.py in _draw_all_if_interactive()
118 def _draw_all_if_interactive():
119 if matplotlib.is_interactive():
--> 120 draw_all()
121
122
ValueError: Image size of 1000x72000 pixels is too large. It must be less than 2^16 in each direction.
The error you encountered is due to trying to create an image that exceeds the maximum pixel dimensions allowed by Matplotlib, and potentially most image-viewing or processing libraries/tools. In your specific case, the error message informs you that the generated image size of 1000x72000 pixels exceeds the maximum permissible size, which is less than 2^16 (65536) in each direction.
This limit is in place to prevent excessive memory usage, which can lead to performance degradation or crashes. Even if it were possible to bypass this limit, displaying such a vast number of images at once would likely not be useful due to the sheer scale and the inability of a human to effectively process that much visual information at once.
Given this limitation, if you need to inspect or process all images, consider the following alternatives:
Alternative 1: Display Images in Batches
Rather than attempting to display all images at once, process and display them in manageable batches. Here's a simple modification of your function to do this:
def display_images_in_batches(X_train, y_train_seg, y_train_class, label_encoder, batch_size=10):
total_batches = len(X_train) // batch_size + (1 if len(X_train) % batch_size != 0 else 0)
for batch in range(total_batches):
start_index = batch * batch_size
end_index = min(start_index + batch_size, len(X_train))
current_batch_size = end_index - start_index
fig, axes = plt.subplots(current_batch_size, 2, figsize=(10, current_batch_size * 5))
for i in range(current_batch_size):
index = start_index + i
original_label = label_encoder.inverse_transform([np.argmax(y_train_class[index])])[0]
if current_batch_size == 1:
ax1, ax2 = axes[0], axes[1] # If only one image in the batch
else:
ax1, ax2 = axes[i]
ax1.imshow(cv2.cvtColor(X_train[index], cv2.COLOR_BGR2RGB))
ax1.title.set_text(f'Original Image: {original_label}')
ax1.axis('off')
ax2.imshow(y_train_seg[index].reshape(image_size, image_size), cmap='gray')
ax2.title.set_text('Segmentation Mask')
ax2.axis('off')
plt.tight_layout()
plt.show()
input("Press Enter to continue to the next batch...") # Pause between batches
This function displays images in batches, pausing between each batch until you press Enter. Adjust the batch_size as needed to fit within the display and memory constraints.
Alternative 2: Save Images to Files
If visual inspection isn't the primary goal (e.g., you're processing images for a report or presentation), consider saving images to disk instead. Iterate through your dataset and save each image and segmentation mask to a file. This provides the opportunity for manual review later, without overwhelming system resources:
def save_images_to_disk(X_train, y_train_seg, y_train_class, label_encoder, output_dir="output_images"):
import os
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for i in range(len(X_train)):
original_label = label_encoder.inverse_transform([np.argmax(y_train_class[i])])[0]
img_filename = f"{output_dir}/img_{i}_{original_label}.png"
mask_filename = f"{output_dir}/mask_{i}_{original_label}.png"
img = cv2.cvtColor(X_train[i], cv2.COLOR_BGR2RGB)
cv2.imwrite(img_filename, img)
mask = (y_train_seg[i].reshape(image_size, image_size) * 255).astype('uint8')
cv2.imwrite(mask_filename, mask)
This saves each image and its mask to the specified output_dir directory, allowing for individual inspection and usage.