0

I have a logical matrix:

0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0
0,0,0,1,1,1,1,1,0,0,0
0,0,0,1,1,1,1,1,1,0,0
0,0,1,1,1,1,1,1,1,0,0
0,0,1,1,1,1,1,1,1,0,0
0,0,1,1,1,1,1,1,1,0,0
0,0,0,1,1,1,1,1,1,0,0
0,0,0,0,1,1,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0

and I would like to fit an ellipse as best as possible and calculate the error. The error could be the elementwise difference between the original data and the best ellipse found.

I have seen the following method: MATLAB Curve Fitting (Ellipse-like)

but I am not sure that is the shortest way to do it.

How would you recommend to find the closest elliptical logical matrix?

Community
  • 1
  • 1
Timothée HENRY
  • 14,294
  • 21
  • 96
  • 136
  • I think [this File Exchange submission](http://www.mathworks.com/matlabcentral/fileexchange/34767-a-suite-of-minimal-bounding-objects) will work very well for this task. – chappjc Feb 24 '14 at 18:33

2 Answers2

1

Find the ellipse 6 DOF parameters:

    %get edge locations
    md = m-imerode(m,ones(3));
    md = padarray(md,10);axis equal

%find edges x,y
[y,x] = find(md);
%fit to Q = a*x^2 + b*y^2 + 2*c*x*y + 2*d*x + 2*e*y + f
H=[x.*x y.*y 2*x.*y x y x*0+1];
 [v,g]=eig(H'*H);


a = v(1,1);
b = v(2,1);
c = v(3,1);
d = v(4,1);
e = v(5,1);
f = v(6,1);

[xg, yg] = meshgrid(1:size(md,2),1:size(md,1));
ev = a*xg.^2+b*yg.^2+2*c*xg.*yg+d*xg+e*yg+f;
 imagesc(ev);axis equal
Mercury
  • 1,886
  • 5
  • 25
  • 44
0

I would fist extract the boundary of your logical ellipse. Iterate the following function from i=2 to n-1, j=2 to m-1, for [n,m]=size(M). It will give you the "boundary matrix", where the boundary is represented by 1 and 0 for others. Then use the method described in here to get the coefficients of the ellipse equation. Note that the matrix indices start from top-left. So you may need to modify the index ordering depending on where you want the origin to be.

function [ bd ] = logical_neighbor( loM, i, j )

bd=0;

if loM(i,j) == 0
    return;
else
    for ni=1:3
        for nj=1:3
            if loM(i-2+ni,j-2+nj) == 0
                bd= 1;
                return;
            end
        end
    end
end

end
Community
  • 1
  • 1
ysakamoto
  • 2,512
  • 1
  • 16
  • 22