Pretty easy. Threshold, fill holes, take the 3 largest.
Solution below. Adapt as needed.
clc;
close all;
clear;
workspace;
format long g;
format compact;
fontSize = 14;
filename = fullfile(pwd, 'image_1.jpg');
grayImage = imread(filename);
if ndims(grayImage) == 3
grayImage = rgb2gray(grayImage);
end
subplot(2, 3, 1);
imshow(grayImage, []);
title('Original Image', 'FontSize', fontSize);
subplot(2, 3, 2);
imhist(grayImage);
grid on;
title('Histogram', 'FontSize', fontSize);
mask = grayImage < 128;
subplot(2, 3, 3);
imshow(mask, []);
title('Initial Binary Image', 'FontSize', fontSize);
mask = imfill(mask, 'holes');
subplot(2, 3, 4);
imshow(mask, []);
title('After holes filled', 'FontSize', fontSize);
mask = ~bwareafilt(mask, 3);
subplot(2, 3, 5);
imshow(mask, []);
title('Final Image Showing 3 Largest', 'FontSize', fontSize);
Best Answer