a b/functions/functions_ellipse/fit_ellipse.m
1
function ellipse_t = fit_ellipse(x, y, im, filename, mask, dirResults, plotta, savefile)
2
%
3
% fit_ellipse - finds the best fit to an ellipse for the given set of points.
4
%
5
% Format:   ellipse_t = fit_ellipse( x,y,axis_handle )
6
%
7
% Input:    x,y         - a set of points in 2 column vectors. AT LEAST 5 points are needed !
8
%           axis_handle - optional. a handle to an axis, at which the estimated ellipse 
9
%                         will be drawn along with it's axes
10
%
11
% Output:   ellipse_t - structure that defines the best fit to an ellipse
12
%                       a           - sub axis (radius) of the X axis of the non-tilt ellipse
13
%                       b           - sub axis (radius) of the Y axis of the non-tilt ellipse
14
%                       phi         - orientation in radians of the ellipse (tilt)
15
%                       X0          - center at the X axis of the non-tilt ellipse
16
%                       Y0          - center at the Y axis of the non-tilt ellipse
17
%                       X0_in       - center at the X axis of the tilted ellipse
18
%                       Y0_in       - center at the Y axis of the tilted ellipse
19
%                       long_axis   - size of the long axis of the ellipse
20
%                       short_axis  - size of the short axis of the ellipse
21
%                       status      - status of detection of an ellipse
22
%
23
% Note:     if an ellipse was not detected (but a parabola or hyperbola), then
24
%           an empty structure is returned
25
26
% =====================================================================================
27
%                  Ellipse Fit using Least Squares criterion
28
% =====================================================================================
29
% We will try to fit the best ellipse to the given measurements. the mathematical
30
% representation of use will be the CONIC Equation of the Ellipse which is:
31
% 
32
%    Ellipse = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f = 0
33
%   
34
% The fit-estimation method of use is the Least Squares method (without any weights)
35
% The estimator is extracted from the following equations:
36
%
37
%    g(x,y;A) := a*x^2 + b*x*y + c*y^2 + d*x + e*y = f
38
%
39
%    where:
40
%       A   - is the vector of parameters to be estimated (a,b,c,d,e)
41
%       x,y - is a single measurement
42
%
43
% We will define the cost function to be:
44
%
45
%   Cost(A) := (g_c(x_c,y_c;A)-f_c)'*(g_c(x_c,y_c;A)-f_c)
46
%            = (X*A+f_c)'*(X*A+f_c) 
47
%            = A'*X'*X*A + 2*f_c'*X*A + N*f^2
48
%
49
%   where:
50
%       g_c(x_c,y_c;A) - vector function of ALL the measurements
51
%                        each element of g_c() is g(x,y;A)
52
%       X              - a matrix of the form: [x_c.^2, x_c.*y_c, y_c.^2, x_c, y_c ]
53
%       f_c            - is actually defined as ones(length(f),1)*f
54
%
55
% Derivation of the Cost function with respect to the vector of parameters "A" yields:
56
%
57
%   A'*X'*X = -f_c'*X = -f*ones(1,length(f_c))*X = -f*sum(X)
58
%
59
% Which yields the estimator:
60
%
61
%       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
62
%       |  A_least_squares = -f*sum(X)/(X'*X) ->(normalize by -f) = sum(X)/(X'*X)  |
63
%       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
64
%
65
% (We will normalize the variables by (-f) since "f" is unknown and can be accounted for later on)
66
%  
67
% NOW, all that is left to do is to extract the parameters from the Conic Equation.
68
% We will deal the vector A into the variables: (A,B,C,D,E) and assume F = -1;
69
%
70
%    Recall the conic representation of an ellipse:
71
% 
72
%       A*x^2 + B*x*y + C*y^2 + D*x + E*y + F = 0
73
% 
74
% We will check if the ellipse has a tilt (=orientation). The orientation is present
75
% if the coefficient of the term "x*y" is not zero. If so, we first need to remove the
76
% tilt of the ellipse.
77
%
78
% If the parameter "B" is not equal to zero, then we have an orientation (tilt) to the ellipse.
79
% we will remove the tilt of the ellipse so as to remain with a conic representation of an 
80
% ellipse without a tilt, for which the math is more simple:
81
%
82
% Non tilt conic rep.:  A`*x^2 + C`*y^2 + D`*x + E`*y + F` = 0
83
%
84
% We will remove the orientation using the following substitution:
85
%   
86
%   Replace x with cx+sy and y with -sx+cy such that the conic representation is:
87
%   
88
%   A(cx+sy)^2 + B(cx+sy)(-sx+cy) + C(-sx+cy)^2 + D(cx+sy) + E(-sx+cy) + F = 0
89
%
90
%   where:      c = cos(phi)    ,   s = sin(phi)
91
%
92
%   and simplify...
93
%
94
%       x^2(A*c^2 - Bcs + Cs^2) + xy(2A*cs +(c^2-s^2)B -2Ccs) + ...
95
%           y^2(As^2 + Bcs + Cc^2) + x(Dc-Es) + y(Ds+Ec) + F = 0
96
%
97
%   The orientation is easily found by the condition of (B_new=0) which results in:
98
% 
99
%   2A*cs +(c^2-s^2)B -2Ccs = 0  ==> phi = 1/2 * atan( b/(c-a) )
100
%   
101
%   Now the constants   c=cos(phi)  and  s=sin(phi)  can be found, and from them
102
%   all the other constants A`,C`,D`,E` can be found.
103
%
104
%   A` = A*c^2 - B*c*s + C*s^2                  D` = D*c-E*s
105
%   B` = 2*A*c*s +(c^2-s^2)*B -2*C*c*s = 0      E` = D*s+E*c 
106
%   C` = A*s^2 + B*c*s + C*c^2
107
%
108
% Next, we want the representation of the non-tilted ellipse to be as:
109
%
110
%       Ellipse = ( (X-X0)/a )^2 + ( (Y-Y0)/b )^2 = 1
111
%
112
%       where:  (X0,Y0) is the center of the ellipse
113
%               a,b     are the ellipse "radiuses" (or sub-axis)
114
%
115
% Using a square completion method we will define:
116
%       
117
%       F`` = -F` + (D`^2)/(4*A`) + (E`^2)/(4*C`)
118
%
119
%       Such that:    a`*(X-X0)^2 = A`(X^2 + X*D`/A` + (D`/(2*A`))^2 )
120
%                     c`*(Y-Y0)^2 = C`(Y^2 + Y*E`/C` + (E`/(2*C`))^2 )
121
%
122
%       which yields the transformations:
123
%       
124
%           X0  =   -D`/(2*A`)
125
%           Y0  =   -E`/(2*C`)
126
%           a   =   sqrt( abs( F``/A` ) )
127
%           b   =   sqrt( abs( F``/C` ) )
128
%
129
% And finally we can define the remaining parameters:
130
%
131
%   long_axis   = 2 * max( a,b )
132
%   short_axis  = 2 * min( a,b )
133
%   Orientation = phi
134
%
135
%
136
137
%Ohad Gal (2019). 
138
%fit_ellipse (https://www.mathworks.com/matlabcentral/fileexchange/3215-fit_ellipse), 
139
%MATLAB Central File Exchange. Retrieved December 17, 2019.
140
141
% initialize
142
orientation_tolerance = 1e-3;
143
144
% empty warning stack
145
warning( '' );
146
147
% prepare vectors, must be column vectors
148
x = x(:);
149
y = y(:);
150
151
% remove bias of the ellipse - to make matrix inversion more accurate. (will be added later on).
152
mean_x = mean(x);
153
mean_y = mean(y);
154
x = x-mean_x;
155
y = y-mean_y;
156
157
% the estimation for the conic equation of the ellipse
158
X = [x.^2, x.*y, y.^2, x, y ];
159
a = sum(X)/(X'*X);
160
161
% check for warnings
162
if ~isempty( lastwarn )
163
    disp( 'stopped because of a warning regarding matrix inversion' );
164
    ellipse_t = [];
165
    return
166
end
167
168
% extract parameters from the conic equation
169
[a,b,c,d,e] = deal( a(1),a(2),a(3),a(4),a(5) );
170
171
% remove the orientation from the ellipse
172
if ( min(abs(b/a),abs(b/c)) > orientation_tolerance )
173
    
174
    orientation_rad = 1/2 * atan( b/(c-a) );
175
    cos_phi = cos( orientation_rad );
176
    sin_phi = sin( orientation_rad );
177
    [a,b,c,d,e] = deal(...
178
        a*cos_phi^2 - b*cos_phi*sin_phi + c*sin_phi^2,...
179
        0,...
180
        a*sin_phi^2 + b*cos_phi*sin_phi + c*cos_phi^2,...
181
        d*cos_phi - e*sin_phi,...
182
        d*sin_phi + e*cos_phi );
183
    [mean_x,mean_y] = deal( ...
184
        cos_phi*mean_x - sin_phi*mean_y,...
185
        sin_phi*mean_x + cos_phi*mean_y );
186
else
187
    orientation_rad = 0;
188
    cos_phi = cos( orientation_rad );
189
    sin_phi = sin( orientation_rad );
190
end
191
192
% check if conic equation represents an ellipse
193
test = a*c;
194
switch (1)
195
case (test>0),  status = '';
196
case (test==0), status = 'Parabola found';  warning( 'fit_ellipse: Did not locate an ellipse' );
197
case (test<0),  status = 'Hyperbola found'; warning( 'fit_ellipse: Did not locate an ellipse' );
198
end
199
200
% if we found an ellipse return it's data
201
if (test>0)
202
    
203
    % make sure coefficients are positive as required
204
    if (a<0), [a,c,d,e] = deal( -a,-c,-d,-e ); end
205
    
206
    % final ellipse parameters
207
    X0          = mean_x - d/2/a;
208
    Y0          = mean_y - e/2/c;
209
    F           = 1 + (d^2)/(4*a) + (e^2)/(4*c);
210
    [a,b]       = deal( sqrt( F/a ),sqrt( F/c ) );    
211
    long_axis   = 2*max(a,b);
212
    short_axis  = 2*min(a,b);
213
214
    % rotate the axes backwards to find the center point of the original TILTED ellipse
215
    R           = [ cos_phi sin_phi; -sin_phi cos_phi ];
216
    P_in        = R * [X0;Y0];
217
    X0_in       = P_in(1);
218
    Y0_in       = P_in(2);
219
    
220
    % pack ellipse into a structure
221
    ellipse_t = struct( ...
222
        'a',a,...
223
        'b',b,...
224
        'phi',orientation_rad,...
225
        'X0',X0,...
226
        'Y0',Y0,...
227
        'X0_in',X0_in,...
228
        'Y0_in',Y0_in,...
229
        'long_axis',long_axis,...
230
        'short_axis',short_axis,...
231
        'status','' );
232
else
233
    % report an empty structure
234
    ellipse_t = struct( ...
235
        'a',[],...
236
        'b',[],...
237
        'phi',[],...
238
        'X0',[],...
239
        'Y0',[],...
240
        'X0_in',[],...
241
        'Y0_in',[],...
242
        'long_axis',[],...
243
        'short_axis',[],...
244
        'status',status );
245
end
246
247
% check if we need to plot an ellipse with it's axes.
248
if plotta
249
    
250
    % rotation matrix to rotate the axes with respect to an angle phi
251
    R = [ cos_phi sin_phi; -sin_phi cos_phi ];
252
    
253
    % the axes
254
    ver_line        = [ [X0 X0]; Y0+b*[-1 1] ];
255
    horz_line       = [ X0+a*[-1 1]; [Y0 Y0] ];
256
    new_ver_line    = R*ver_line;
257
    new_horz_line   = R*horz_line;
258
    
259
    % the ellipse
260
    theta_r         = linspace(0,2*pi);
261
    ellipse_x_r     = X0 + a*cos( theta_r );
262
    ellipse_y_r     = Y0 + b*sin( theta_r );
263
    rotated_ellipse = R * [ellipse_x_r;ellipse_y_r];
264
    
265
    axis_handle = figure;
266
    imshow(im2double(im) + edge(mask))
267
    hold on
268
    plot(X0_in, Y0_in, 'rx', 'MarkerSize', 10);
269
    
270
    % draw
271
    hold_state = get( axis_handle,'NextPlot' );
272
    set( axis_handle,'NextPlot','add' );
273
    plot( new_ver_line(1,:),new_ver_line(2,:),'r' );
274
    plot( new_horz_line(1,:),new_horz_line(2,:),'r' );
275
    plot( rotated_ellipse(1,:),rotated_ellipse(2,:),'r' );
276
    set( axis_handle,'NextPlot',hold_state );
277
    
278
    str = [filename ' ; ellipse fitting'];
279
    
280
    title(str, 'Interpreter', 'none')
281
    
282
    if savefile
283
        export_fig(gcf, [dirResults str '.jpg']);
284
    end %if save
285
    
286
end %if plotta
287
288