clc;
close all;
clear;
workspace;
format long g;
format compact;
fontSize = 20;
folder = pwd;
baseFileName = 'i.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);
[rows, columns, numberOfColorChannels] = size(rgbImage)
if numberOfColorChannels > 1
grayImage = rgbImage(:, :, 2);
else
grayImage = rgbImage;
end
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
clippedImage = grayImage;
clippedImage(:, 1200:end) = grayImage(1,1);
subplot(2, 2, 2);
[counts, grayLevels] = histcounts(clippedImage(:));
counts(counts == max(counts)) = 0;
bar(grayLevels(1:end-1), counts);
grid on;
title('Histogram of Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
binaryImage = clippedImage >= 245;
binaryImage = bwareafilt(binaryImage, 1);
binaryImage = bwconvhull(binaryImage);
subplot(2, 2, 3);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
boundaries = bwboundaries(binaryImage);
xBoundary = boundaries{1}(:, 2);
yBoundary = boundaries{1}(:, 1);
xRight = zeros(1, columns);
yRight = zeros(1, columns);
for row = 1 : rows
x = find(binaryImage(row, :), 1, 'last');
if ~isempty(x)
xRight(row) = x;
yRight(row) = row;
end
end
noObjectRows = xRight == 0;
xRight(noObjectRows) = [];
yRight(noObjectRows) = [];
[xCenter, yCenter, R, a] = circfit(xRight,yRight);
subplot(2, 2, 4);
imshow(grayImage, []);
title('Original Image with Disc Circled', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
viscircles([xCenter, yCenter], R);
function [xc,yc,R,a] = circfit(x,y)
n=length(x); xx=x.*x; yy=y.*y; xy=x.*y;
A=[sum(x) sum(y) n;sum(xy) sum(yy) sum(y);sum(xx) sum(xy) sum(x)];
B=[-sum(xx+yy) ; -sum(xx.*y+yy.*y) ; -sum(xx.*x+xy.*y)];
a=A\B;
xc = -.5*a(1);
yc = -.5*a(2);
R = sqrt((a(1)^2+a(2)^2)/4-a(3));
end
Best Answer