clc;
close all;
clearvars;
workspace;
format long g;
format compact;
fontSize = 20;
folder = pwd;
baseFileName = 'image.png';
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
fullFileNameOnSearchPath = baseFileName;
if ~exist(fullFileNameOnSearchPath, 'file')
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
grayImage = grayImage(:, :, 1);
end
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo;
axis('on', 'image');
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
drawnow;
binaryImage = grayImage < 200;
[labeledImage, numberOfRegions] = bwlabel(binaryImage);
fprintf('Found %d regions.\n',numberOfRegions);
subplot(2, 2, 2);
imshow(binaryImage, []);
caption = sprintf('Binary Image with %d Blobs', numberOfRegions);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo;
axis('on', 'image');
coloredLabels = label2rgb (labeledImage, 'hsv', 'k', 'shuffle');
subplot(2, 2, 3);
imshow(coloredLabels);
axis('on', 'image');
caption = sprintf('Pseudo colored labels, from label2rgb().\nBlobs are numbered from top to bottom, then from left to right.');
title(caption, 'FontSize', fontSize);
props = regionprops(labeledImage, 'BoundingBox', 'Area');
subplot(2, 2, 4);
imshow(binaryImage, []);
title('Binary Image with Bounding Boxes', 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo;
axis('on', 'image');
hold on;
for k = 1 : length(props)
thisBB = props(k).BoundingBox;
fprintf('Blob #%d has a blob area of %.1f and BoundingBox area of %.1f',...
props(k).Area, thisBB(3)*thisBB(4));
rectangle('Position', thisBB, 'EdgeColor', 'r', 'LineWidth', 3);
end
Best Answer