Clear Filters
Clear Filters

How to close small holes inside each blob?

3 views (last 30 days)
Hi,
I have attached two images above. The 140_multiplied.jpg is the original image. I plan to close the small holes inside the regions. I tried the code below. But the result is shown in 140_multiplied_closed.jpg which is not correct as it changes the shape of the regions. Any suggestions would be appreciated. Thank you.
result_img=imread('140_multiplied.jpg');
% Close the holes in the regions of the result image
result_img_filled = imfill(result_img, 'holes');
result_img_closed = imclose(result_img_filled, strel('disk', 5)); % Adjust the disk size as needed
  1 Comment
DGM
DGM on 18 Apr 2024
Edited: DGM on 18 Apr 2024
Morphological closing with imclose() will change the mask shape dependent on the shape of the structuring element.
You can use imfill() to close all holes that aren't connected to the image edge.
If you only want to fill holes below a certain size, you can try something like
% get rid of holes below a certain size
minimumholearea = 25; % area in pixels
mask = ~bwareaopen(~mask,minimumholearea);

Sign in to comment.

Accepted Answer

Cris LaPierre
Cris LaPierre on 18 Apr 2024
Edited: Cris LaPierre on 18 Apr 2024
I htink the issue is that your image needs to be converted to a grayscale image first. Here's some code I generated using the Image Segmenter app.
img = imread('140_multiplied.jpg');
% Threshold image with global threshold
BW = imbinarize(im2gray(img));
% Fill holes
BW = imfill(BW, 'holes');
% Show results
imshowpair(img,BW,'montage')
If you need the result to be RGB, then the following code will do that.
RGB = img;
RGB(repmat(BW,[1 1 3]))=255;
imshowpair(RGB,img) % Green shows the difference

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!