I am trying to to pull bounding box and area data from segmented masks. For the mask shown below, instead of correcting proposing 5 bounding boxes, regionprops proposes 2394 bounding boxes. The image/mask is a binary numpy array with values of either 0 or 1. What can I do so that skimage.measure.regionprops proposes the correct number of bounding boxes? Most of the bounding boxes generated have an area of 1 pixel.
would you mind sharing the code you executed and an example image so that we can have a look what might go wrong?
The image is the ‘Mask.’
from skimage.io import imread import matplotlib.pyplot as plt from skimage.segmentation import mark_boundaries from skimage.measure import label, regionprops, find_contours import cv2 import os import numpy as np from PIL import Image import matplotlib.pyplot as plt img = Image.open("Mask_Data/10_10_predicted_mask.jpg") mask_labels = label(np.asarray(img)) props = regionprops(mask_labels) img_copy = np.asarray(img) for prop in props: if prop.bbox_area > 0: cv2.rectangle(img_copy, (prop.bbox, prop.bbox), (prop.bbox, prop.bbox), (145, 0, 0), 2) fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize = (15, 5)) ax1.imshow(img) ax1.set_title('Image') ax2.set_title('Mask') ax3.set_title('Image with derived bounding box') ax2.imshow(img, cmap='gray') ax3.imshow(img_copy) plt.show()
would you mind sharing the example image “Mask_Data/10_10_predicted_mask.jpg” so that we can have a look what might go wrong?
I think the problem is that you use a mask that was saved in a jpg format. jpg is compressing information and sort of resampling your binary mask, thus creating an image that is not a mask and has weird features (like that box, typical of jpg compression). I made a small example using the imagej blobs picture. I created a mask and saved it once as jpg and once as tif. Then I labelled both with skimage. This just shows the regions to identify:
This shows the labelled image based on a jpg image:
And finally this shows the labelled image based on a tif image:
So I think you can solve your problem by simply saving your masks as tif files and not jpg.
That seems to have fixed it! Thank you so much! Would have never figured that out.