MATLAB Answers

How to fit an ellipse to an image in matlab.

155 views (last 30 days)
diskimage1.jpgI have a image like this and I want to fit an ellipse around this disk image and get the info about the ellipse like its axis, center point, etc. I am unsure how to use the image proccessing toolbox to draw an ellipse to it and get info about the ellipse.

  0 Comments

Sign in to comment.

Accepted Answer

Akira Agata
Akira Agata on 11 Dec 2019
How about the following?
% Read image
I = imread('diskimage1.jpeg');
% Binarize
Igray = rgb2gray(I);
BW = imbinarize(Igray);
% Extract the maximum area
BW = imclearborder(BW);
BW = bwareafilt(BW,1);
% Calculate centroid, orientation and major/minor axis length of the ellipse
s = regionprops(BW,{'Centroid','Orientation','MajorAxisLength','MinorAxisLength'});
% Calculate the ellipse line
theta = linspace(0,2*pi);
col = (s.MajorAxisLength/2)*cos(theta);
row = (s.MinorAxisLength/2)*sin(theta);
M = makehgtform('translate',[s.Centroid, 0],'zrotate',deg2rad(-1*s.Orientation));
D = M*[col;row;zeros(1,numel(row));ones(1,numel(row))];
% Visualize the result
figure
imshow(Igray)
hold on
plot(D(1,:),D(2,:),'r','LineWidth',2)
untitled.png

  6 Comments

Show 3 older comments
UgiLishes
UgiLishes on 29 Jun 2020
Hi Akira,
Thank you very much for your code, I have found it to be very helpful!
can I ask you a follow up question?
I used your cade to fit an ellipse to my CT scan and I works really well but there is one more thing I'd like to do: find goodness of fit to my image. as you can see in the attached file the bottom of the image doesn't fit so well. what can I do to quantify how well the ellipse fits my image?
thank you very much
Image Analyst
Image Analyst on 29 Jun 2020
You can get the boundary of your binary image with bwboundaries. Then use sqrt() to find the distance of every actual boundary point to the closest fit point. Find the closest one with min. Then take the mean or sum of those closest distances.
boundaries = bwboundaries(mask);
boundaries = boundaries{1}; % Extract from cell
xb = boundaries(:, 2);
yb = boundaries(:, 1);
closestDistances = zeros(1, length(xb));
for k = 1 : length(xb)
% Get distance of each actual boundary point to all points in your ellipse fit vectors.
distances = sqrt((xFit - xb(k)) .^ 2 + (yFit - yb(k)) .^ 2); % A vector of distances
closestDistances(k) = min(distances); % A single distance.
end
closenessOfFitMetric = mean(closestDistances)

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by