clc;
close all;
clear;
workspace;
format long g;
format compact;
fontSize = 20;
baseFileName = 'coins.png';
folder = fileparts(which('cameraman.tif'));
fullFileName = fullfile(folder, baseFileName);
grayImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
grayImage = grayImage(:, :, 2);
end
subplot(3, 3, 1);
imshow(grayImage, []);
caption = sprintf('Original Grayscale Image, %s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
subplot(3, 3, 2);
histogram(grayImage);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
binaryImage = grayImage > 80;
binaryImage = imfill(binaryImage, 'holes');
binaryImage = bwareaopen(binaryImage, 150);
subplot(3, 3, 3);
imshow(binaryImage, []);
axis on;
caption = sprintf('Binary Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
[labeledImage, numBlobs] = bwlabel(binaryImage);
props = regionprops(labeledImage, 'Area');
allAreas = [props.Area]
smallBlobIndexes = find(allAreas < 2000)
bigBlobIndexes = find(allAreas >= 2000)
smallBlobsImage = ismember(labeledImage, smallBlobIndexes);
subplot(3, 3, 4);
imshow(smallBlobsImage, []);
title('Small blobs', 'FontSize', fontSize);
axis image;
hold on;
bigBlobsImage = ismember(labeledImage, bigBlobIndexes);
subplot(3, 3, 5);
imshow(bigBlobsImage, []);
title('Big blobs', 'FontSize', fontSize);
axis image;
hold on;
radius = 5;
se = strel('disk', radius, 0);
smallBlobsImage = imdilate(smallBlobsImage, se);
subplot(3, 3, 7);
imshow(smallBlobsImage, []);
title('Small blobs Dilated', 'FontSize', fontSize);
axis image;
hold on;
se = strel('disk', radius, 0);
bigBlobsImage = imerode(bigBlobsImage, se);
subplot(3, 3, 8);
imshow(bigBlobsImage, []);
title('Big blobs eroded', 'FontSize', fontSize);
axis image;
hold on;
finalImage = smallBlobsImage | bigBlobsImage;
subplot(3, 3, [6,9]);
imshow(finalImage, []);
title('Final image', 'FontSize', fontSize);
axis image;
hold on;
Best Answer