clc;
close all;
clear;
workspace;
format long g;
format compact;
fontSize = 20;
folder = pwd;
baseFileName = 'imperfect circles.jpg';
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
rgbImage = imread(fullFileName);
subplot(2, 3, 1);
imshow(rgbImage, []);
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
[rows, columns, numberOfColorChannels] = size(rgbImage)
if numberOfColorChannels > 1
grayImage = rgbImage(:, :, 2);
else
grayImage = rgbImage;
end
subplot(2, 3, 2);
[counts, binLocations] = imhist(grayImage);
counts(1) = 0;
bar(binLocations, counts);
grid on;
title('Histogram of Image', 'FontSize', fontSize, 'Interpreter', 'None');
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
binaryImage = grayImage > 128;
binaryImage(end-1:end, :) = false;
se = strel('disk', 5, 0);
binaryImage = imclose(binaryImage, se);
binaryImage = imfill(binaryImage, 'holes');
subplot(2, 3, 3);
imshow(binaryImage, []);
title('Initial Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
drawnow;
binaryImage = bwareaopen(binaryImage, 1000);
subplot(2, 3, 4);
imshow(binaryImage, []);
title('Closed Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
drawnow;
binaryImage = bwconvhull(binaryImage, 'objects');
subplot(2, 3, 5);
imshow(binaryImage, []);
title('Final Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
drawnow;
finalImage = grayImage;
finalImage(~binaryImage) = 0;
subplot(2, 3, 6);
imshow(finalImage, []);
title('Final, Masked Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
title('Outlines, from bwboundaries()', 'FontSize', fontSize);
axis image;
hold on;
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), 'g', 'LineWidth', 2);
end
hold off;
props = regionprops(binaryImage, 'Centroid', 'EquivDiameter');
xyCentroids = [props.Centroid];
xCentroids = xyCentroids(1:2:end)
yCentroids = xyCentroids(2:2:end)
hold on;
for k = 1 : length(xCentroids)
thisX = xCentroids(k);
thisY = yCentroids(k);
thisDiameter = props(k).EquivDiameter;
plot(thisX, thisY, 'r+', 'MarkerSize', thisDiameter, 'LineWidth', 2);
end