How to find the diameter of a circle from an image ?
38 views (last 30 days)
Show older comments
I tried to find the diameter of a circle through an image using two codes
1) regionprops()
2) imdistline()
The diameter in the image is 100mm. The answer differs everytime I change the code. Can anyone tell me where I went wrong ?
-- region props code
% read the image
a = imread('circle6.jpeg');
% convert the image
b = rgb2gray(a);
be = imbinarize(b);
figure(2),imshow(be);
% using regionprops
stats = regionprops('table',be, 'Area','EquivDiameter','Perimeter');
% storing the values in other variables
x = stats.Area;
y = stats.EquivDiameter;
z = stats.Perimeter;
%using area to find the diameter
r = sqrt(x/(4*pi))*0.2645;
%using perimeter
r1 =( z/(4*pi))*0.2645;
% using equivDiameter
r3 = y*0.2645;
-- imdistline()
a = imread('circle6.jpeg');
c = rgb2gray(a);
b = imbinarize(c);
imshow(b);
%measuring
h = imdistline(gca);
api =iptgetapi(h);
%
pause();
%
dist =api.getDistance();
u = menu('Choose measuring unit','Pixels','Centim','Meters');
if (u==1)
fprintf('The length of the object is: %0.2f Pixels\n',dist);
elseif (u==2)
dist_cm = dist*0.2645;
fprintf('The length of the object is: %0.2f Centim\n',dist_cm);
else
dist_m = (dist*0.2645)/100;
fprintf('The length of the object is: %0.2f Meters\n',dist_m);
end
0 Comments
Answers (2)
Image Analyst
on 16 Jun 2020
What you deceptively call y is actually the diameter:
y = stats.EquivDiameter; % y is the diameter.
No need to do anything else. It will not change on each run if the image does not change.
To calibrate, you need to multiply by some spatial calibration factor. If you know the field of view of your image, you can compute it like this
[rows, columns, numberOfColorChannels] = size(a);
pixelsPerMm = imageWidthInMm / columns;
diameter = y * pixelsPerMm
Of course you need to know imageWidthInMm. If you don't, you can use my attached spatial calibration demo to interactively draw a known distance on your image.
2 Comments
Image Analyst
on 19 Jun 2020
You set it equal to the known real world distance
imageWidthInMm = 100; % Known distance of circle in image.
multiply it by the distance in pixels, like I showed you:
pixelsPerMm = imageWidthInMm / columns;
columns is the equivalent circular diameter as gotten from regionprops off a perfectly accurate, undamaged reference circle.
KSSV
on 16 Jun 2020
I = imread("circle6.jpeg") ;
I1 = rgb2gray(I) ;
[y,x] = find(I1~=255) ;
C = [mean(x) mean(y)] ; % Center of circle
dx = C(1)-x ;
dy = C(2)-y ;
d = sqrt(dx.^2+dy.^2) ;
r = max(d) ; % Radius of circle
th = linspace(0,2*pi) ;
xc = C(1)+r*cos(th) ;
yc = C(2)+r*sin(th) ;
imshow(I) ;
hold on
plot(xc,yc,'r')
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!