# How to fit an ellipse to an image in matlab.

71 views (last 30 days)
Hardit Singh on 9 Dec 2019
Commented: Hardit Singh on 12 Dec 2019
I 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.

Akira Agata on 11 Dec 2019
How about the following?
% 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)

Show 1 older comment
Image Analyst on 11 Dec 2019
Akira Agata on 12 Dec 2019
Thank you Image Analyst-san for introducing many sophisticated algorithms!
These well-designed algorithms must be robust for many images. But, as far as this image, I think small modification for my previous code would be OK.
Please change the first half of my previous code as follows:
% Binarize
Igray = rgb2gray(I);
BW = Igray > 10; % <- Changed this line for this new image
% Extract the maximum area
BW = imclearborder(BW);
BW = bwareafilt(BW,1);
BW = imfill(BW,'holes'); % <- Added this line to fill holes
The remaining part is the same as previous one. If you run the code, the result will be like this:
Hardit Singh on 12 Dec 2019
Thank you so much for your help!

### More Answers (1)

Image Analyst on 11 Dec 2019