Bonjour,

Voici un code en python pour ajuster les paramètre d'une ellipse 2D à partir d'un nuage de points.

Le module principale:
Code Python : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
 
""" 2D Ellipse fitting
 
    Fits an ellipse to a set of points (x_i, y_i) using the canonical
    representation:
        
     a * x^2 + b * x * y + c * y^2 + d * x + e * y + f = 0 (1)
    
    Provided features
    -----------------
    
    The module provides several function related to ellipses:
    
    `fit_ellipse`:
        fits an ellipse from a set of points and return the parameters
        of the canonical representation (see above)
        
    `get_parameters`:
        converts canonical parameters into intuitive representation i.e.
        major and minor radii
    
    
    let a_ be the vector a_ = [a, b, c, d, e, f]'
    Let D be the (N x 6) design matrix:
        D = [z_1 z_2 ... z_n]'
        
        where 
        
        z_i = [ x_i^2, x_i * y_i, y_i^2, x_i, y_i, 1 ]'
    
    We want to minimize
    
        E = \sum_i (a_' * z_i)^2 = || D * a_ ||^2 = a_' * S * a
        
        where 
        
        S = D' * D
 
    If equation (1) corresponds to an ellipse we must have:
        
        4 * a * c - b^2 > 0
        
    Since equation (1) is unique up to a scaling factor we can impose:
        
        4 * a * c - b^2 = 1
        
    which can be written in matrix form as:
        
        a_' * C * a_ = 1
        
        with
        
        ::
        
            C = | 0 0  2 0 0 0 |
                | 0 -1 0 0 0 0 |
                | 2 0  0 0 0 0 |
                | 0 0  0 0 0 0 |
                | 0 0  0 0 0 0 |
                | 0 0  0 0 0 0 |
 
    So the problem reduces to:
        
        a_ = argmin a_' S a_
        s.t.                        (2)
            a_' * C * a_ = 1
        
    which is equivalent to solving:
        
        S a_ = l * C * a_           (3)
        
    where l is a Lagrange multiplier.
    
    Equation (2) is just a generalized eigen value problem. And the solution
    to (1) is the eigen vector corresponding to the smallest positive eigen
    value of (2).
    
    It can be prooved that (3) has 2 negative eigen values and one positive.
    The biggest eigen value the corresponds to the solution.
    
    Since C has negative eigen values solvers in scipy/numpy are not able
    to perform the eigen decomposition. To solve (2) we reduce the problem
    to a 3x3 eigen value problem for wich we can solve the problem
    analytically. For that, we split S and C into 3x3 blocks.    
    
    Let's define:
    
    ::
        
        S = | A  B |
            | B' E |
        
        C = | F  0 |
            | 0  0 |
            
        a_ = [x' y']'
        
    Rewritting (3) we get:
        
        A * x + B * y = l * F * x
        B'* x + E * y = 0
        
    which gives:
        
        y = - E^(-1) * B' * x
        (A - B * E^(-1) * B') * x = l * F * x (4)
    
    Equation (4) is a 3x3 eigen value problem that we can solve analytically.
    
    :Notes:
 
        Detailed explanations can be found in:
            
            *Direct Least square fitting of Ellipses*. A. Fitzgibbon, M. Pilu,
            and R. B. Fisher. Pattern Analysis and Machine Intelligence. 1999
 
    :Author: Alexis Mignon (c) 2012
    :E-mail: alexis.mignon@gmail.com
        
"""
 
import numpy as np
from scipy.linalg import inv, eigh, solve
 
def _find_max_eigval(S):
    """
    Finds the biggest generalized eigen value of the system
        
    S * x = l * C * x
        
    where
    
    ::
        
        C = | 0  0 2 |
            | 0 -1 0 |
            | 2  0 1 |
 
    Parameters:
    -----------    
    S : 3x3 matrix
    
    Returns:
    --------
    the highest eigen value
    """
 
    a = S[0,0]
    b = S[0,1]
    c = S[0,2]
    d = S[1,1]
    e = S[1,2]
    f = S[2,2]
 
    # computes the coefficients of the caracteristique polynomial
    # det(S - x * C) = 0
    # Since the matrix is 3x3 we have a 3rd degree polynomial
    # _a * x**3 + _b * x**2 + _c * x + _d
    _a = -4
    _b = 4 * (c - d)
    _c = a * f - 4 * b * e + 4 * c * d - c * c
    _d = a * d * f - b * b * f - a * e * e + 2 * b * c * e - c  * c * d
 
    # computes the roots of the polynomial
    # there must be 2 negative roots and one
    # positive, i.e. the biggest one.
    x2, x1, x0 = sorted(np.roots([_a, _b, _c, _d] ))
    return x0
 
def _find_max_eigvec(S):
    """
    Computes the positive eigen value and the corresponding
    eigen vector of the system:
        
        S * x = l * C * x
    
        where
        ::
        
            C = | 0  0 2 |
                | 0 -1 0 |
                | 2  0 1 |
                
    Parameters:
    -----------    
    S : 3x3 matrix
    
    Returns:
    --------
        (l, u)
    
    l : float
        the positive eigen value
    
    u : the corresponding eigen vector
"""
 
    l = _find_max_eigval(S)
 
    a11 = S[0,0]
    a12 = S[0,1]
    a13 = S[0,2]
    a22 = S[1,1]
    a23 = S[1,2]
 
    u = np.array([
        a12 * a23 - (a13  - 2*l) * (a22 + l),
        a12 * (a13  - 2*l) - a23 * a11,
        a11 * (a22 + l) - a12 * a12
    ])
 
    c = 4 * u[0] * u[2] - u[1] * u[1]
 
    return l, u/np.sqrt(c)
 
def fit_ellipse(X):
    """ Fit an ellipse.
    
    Computes the best least squares parameters of an ellipse  expressed as:
        
        a * x^2 + b * x * y + c * y^2 + d * x + e * y + f = 0
    
    Parameters
    ----------
    X : N x 2 array
        an array of N 2d points.
    
    Returns:
    --------
    an array containing the parameters:
        
        [ a , b, c, d, e, f]
 
"""
    x = X[:,0]
    y = X[:,1]
 
    # building the design matrix
    D = np.vstack([ x*x, x*y, y*y, x, y, np.ones(X.shape[0])]).T
    S = np.dot(D.T, D)
 
    S11 = S[:3][:,:3]
    S12 = S[:3][:,3:]
    S22 = S[3:][:,3:]
 
    S22_inv = inv(S22)
    S22_inv_S21 = np.dot(inv(S22), S12.T)
 
    Sc =  S11 - np.dot(S12, S22_inv_S21)
    l, a = _find_max_eigvec(Sc)
 
    b = - np.dot(S22_inv_S21, a)
 
    return np.hstack([a,b])
 
def create_ellipse(r, xc, alpha, n=100, angle_range=(0,2*np.pi)):
    """ Create points on an ellipse with uniform angle step
    
    Parameters
    ----------
    r: tuple
        (rx, ry): major an minor radii of the ellipse. Radii are supposed to
        be given in descending order. No check will be done.
    xc : tuple
        x and y coordinates of the center of the ellipse
    alpha : float
        angle between the x axis and the major axis of the ellipse
    n : int, optional
        The number of points to create
    angle_range : tuple (a0, a1)
        angles between which points are created.
        
    Returns
    -------
        (n * 2) array of points 
"""
    R = np.array([
        [np.cos(alpha), -np.sin(alpha)],
        [np.sin(alpha), np.cos(alpha)]
    ])
 
    a0,a1 = angle_range
    angles = np.linspace(a0,a1,n)
    X = np.vstack([ np.cos(angles) * r[0], np.sin(angles) * r[1]]).T
    return np.dot(X,R.T) + xc
 
def get_parameters(x):
    """
    Computes 'natural' parameters of an ellipse given the parameters
    of the canonical equation:
        
        a * x^2 + b * x * y + c * y^2 + d * x + e * y + f = 0
    
    Parameters:
    -----------
    x : array_like
        An array of 6 elements corresponding to the coefficients of the
        canonical equation (see above)
    
    Returns:
    --------
        tuple (rx, ry), (xc, yc), alpha
        
    (rx, ry) : tuple
        Radii of the major and minor axes
    
    (xc, yc) : tuple
        coordinates of the center
    
    alpha : float
        angle between the x axis and the major axis
    
    :Note:
 
        Computed the parameters of the ellipse when it is expressed as:
            
            x'^2/rx^2 + y'/ry^2 = 1
            
        where x' and y' correpsond to the rotated coordinates:    
            
            x' =  cos(alpha)(x-xc) + sin(alpha)(y-yc)
            y' = -sin(alpha)(x-xc) + cos(alpha)(y-yc)
        
        Which can be put in matrix form as
        
            (X-Xc)' R D R' (X-Xc) = 1
        
        where
        ::
            
              X = [x y] and Xc = [xc yc]
              
              R = [ cos(alpha) -sin(alpha)]
                  [ sin(alpha) cos(alpha) ]
                  
              D = [ 1/rx^2           0    ]
                  [    0          1/ry^2  ]
                    
        Parameters are given as the parameter of the conic:
            
            a * x^2 + b * x * y + c * y^2 + d * x + e * y + f = 0
        
        In matrix form we have:
            
            X' A X + B' X + f = 0
            
            where
            ::
                  X = [ x  y ]'
            
                  A = [ a b/2]
                      [b/2 c ]
                      
                  B = [ d  e ]'
              
        Any ellipse can be written as:
            
                (X - Xc)' A (X - Xc)  = r^2
                
        which develops in:
            
            X'A X - 2 * Xc' A X + Xc' A Xc - r^2 = 0
            
            So we have:
                
                B = - 2 * A Xc
                
            and
            
                f = Xc' A Xc - r^2
                
            and thus:
                
                Xc = -1/2 * A^(-1) B
                r^2 = Xc' A Xc - f
            
            We also see that
            
            1/r^2 * (X - Xc)' A (X - Xc) = (X-Xc)' R D R' (X-Xc) = 1
            
            By performing eigen decomposition on A = U L U', we obtain
            
                R = U
                
                and 
                
                lx / r^2 = 1/rx^2
                ly / r^2 = 1/ry^2
                
            hence
            
                rx^2 = r^2 / lx
                ry^2 = r^2 / ly
                
            the angle alpha is finally determined using
            ::
                
                U = | u11,  u12 | = | cos(alpha)  sin(alpha)|
                    |-u12,  u22 |   | -sin(alpha) cos(alpha)|
                alpha = sign(u12) * arccos(u11)
    """
    a,b,c,d,e,f = x
 
    A = np.array([
        [ a, b/2 ],
        [b/2, c  ]
    ])    
 
    B = np.array([d,e])    
 
    w,u = eigh(A)
 
    Xc = solve(-2*A,B)
    r2 = -0.5 * np.inner(Xc,B) - f
 
    rr2 = r2 / w
 
    alpha = np.arccos(u[0,0])
    if alpha > np.pi/2:
        alpha = alpha - np.pi
 
    alpha *= np.sign(u[0,1])
 
    return tuple(np.sqrt(rr2)), tuple(Xc), alpha

Et un exemple d'utilisation:
Code Python : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 
# -*- coding: utf-8 -*-
"""
Sample code for the use of fit_ellipse
 
:Author: Alexis Mignon
:E-mail: alexis.mignon@gmail.com
"""
 
import pylab as pl
import numpy as np
from fit_ellipse import create_ellipse, fit_ellipse, get_parameters
 
# ellipse parameters
r = (1.0, 0.5)
xc = (0.5,1.5)
alpha = np.pi/3
 
# points to draw the ellipse
X = create_ellipse(r,xc,alpha)
# points from which we guess the parameters
Xn = create_ellipse(r,xc,alpha, angle_range=(-np.pi/2, np.pi/2), n=10)
# additional gaussian noise
Xn += 0.05 * min(r) * np.random.randn(*Xn.shape)
 
# guess parameters from noised data
a = fit_ellipse(Xn)
rf, xcf, alpha_f = get_parameters(a)
 
# points to draw the guessed ellipse
Xf = create_ellipse(rf,xcf,alpha_f)
 
print "real params:"
print "rx, ry:", r[0],",",r[1]
print "xc, yc:", xc[0],",",xc[1]
print "alpha:", alpha
print    
 
print "found params:"
print "rx, ry:", rf[0],",",rf[1]
print "xc, yc:", xcf[0],",",xcf[1]
print "alpha:", alpha_f
 
# Plot data
pl.scatter(*Xn.T, label="noisy points")
pl.plot(*X.T, label="source ellipse")
pl.plot(*Xf.T, label="guessed ellipse")
pl.legend(loc="lower right")
pl.show()

Vous pouvez récupérer l'ensemble sur :
http://code.google.com/p/fit-ellipse/

La méthode est décrite dans A. Fitzgibbon et al. "Direct Least Square Fitting of Ellipses". Pattern Analysis and Machine Intelligence. 1999.

Voici les grandes lignes de la méthode:

On a la forme paramétrique d'une conique:

F(x,y;a_) = a * x^2 + b * x * y + c * y^2 + d * x + e * y + f = 0

où a_ est le vecteur

a_ = [a, b, c, d, e, f]'

(Le ' dénote la transposition)

Pour une ellipse on doit avoir
b^2 - 4*a*c < 0

Soit d le vecteur d = [ x^2, x*y, y^2, x, y, 1]'

F(x,y; a_) = 0 s'écrit simplement
F(x,y; a_) = a_' d = 0

Donc pour tout point de la conique le produit scalaire a_' d doit être nul.

Comme F(x,y,;a_) = 0 est invariante à un facteur d'échelle prêt on
peut imposer:
4*a*c - b^2 = 1

On a une série de n points (x_i, y_i).

Pour chaque point, a_' d_i est une mesure algébrique de l'écart du point (x_i, y_i) à l'ellipse.

On cherche donc a minimiser l'écart de l'ensemble des points à l'ellipse avec:

min_{a_} \sum_i (a_' d_i)^2
sous contrainte 4*a*c - b^2 = 1

En appelant D la matrice

D = [d_1, ...., d_n]'

on a \sum_i (a_' d_i)^2 = || D * a_ ||^2 = a_ '* D' * D * a_

En posant S = D' D
On a le probème suivant:

min_{a_} a_ '* S * a_
sous contrainte a_' C a_ = 1

où C est la matrice 6x6 où tous les élements vallent 0 sauf pour les éléments:
C[0,2] = 2
C[1,1] = -1
C[2,0] = 2

Avec cette définition de C on a bien a_' C a_ = 4*a*c - b^2

En dérivant la fonction à minimiser et la contrainte est en introduisant le multiplicateur de Lagrange l, on obtient le problème équivalent:

S * a_ = l * C * a_

qui est une équation aux valeur propre généralisée.

Les auteurs du papier de référence montre qu'il y a toujours 2 valeurs propres positives et une négative (les autres sont nulles) et que la solution correspond à l'unique valeur propre positive.

Un souci qui se pose est que les fonctions pour résoudre le problème:

A x = l * B * x

fournies dans scipy ne gèrent que les cas où B est semi-définie positive
or les valeur propre de C sont [2,0,-1,-2]. Ce n'est donc pas le cas.

Pour résoudre le problème, j'ai décomposé S et C en sous blocks 3x3.
Comme le seul sous-block 3x3 de C non nul est le premier on peut se ramener à un problème aux valeurs propres généralisée avec des matrices 3x3, qu'il est facile de résoudre analytiquement. Le détail est donnée dans la documentation du code.

En espérant que ce soit utile.