-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDSHG_ellipse_JFP_v301.py
241 lines (185 loc) · 7.39 KB
/
DSHG_ellipse_JFP_v301.py
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
import numpy as np
import numpy.linalg as la
__version__ = '3.0.1'
class LsqEllipse:
"""Lest Squares fitting of Elliptical data
Attributes
----------
coef_ : array
Estimated coefficients for the Least squares fit to the elliptical data
containing the values [a,b,c,d,f,g].T corresponding to
ax**2 + 2bxy + cy**2 + 2dx + 2fy + g
References
----------
(*) Halir R., Flusser J. 'Numerically Stable Direct Least Squares
Fitting of Ellipses'
(**) Weisstein, Eric W. "Ellipse." From MathWorld--A Wolfram Web Resource.
http://mathworld.wolfram.com/Ellipse.html
Examples
--------
>>> import numpy as np
>>> from sklearn.linear_model import LsqEllipse
>>> x = np.array([ 1., 0., -1., -0., 1.])
>>> y = np.array([ 0. , 0.5, 0. , -0.5, -0. ])
>>> X = np.c_[x, y]
>>> reg = LsqEllipse().fit(X)
>>> reg.as_parameters()
"""
ALLOWED_FEATURES = 2
def __init__(self):
self.coef_ = None
def _check_data(self, X):
n_samples, n_features = X.shape
if not n_features == self.ALLOWED_FEATURES:
raise ValueError("Incorrect number of features. "
f"Got {n_features} features, expected 2. ")
if n_samples < 5:
raise ValueError("Received too few samples"
f"Got {n_samples} features, 5 or more required. ")
return X
def fit(self, X):
"""Fit the data
Parameters
----------
X : array, shape (n_points, 2)
Data values for the x-y data pairs to fit
Returns
-------
self : returns an instance of self.
"""
X = self._check_data(X)
# extract x-y pairs
x, y = X.T
# Quadratic part of design matrix [eqn. 15] from (*)
D1 = np.vstack([x*x, x * y, y*y]).T
# Linear part of design matrix [eqn. 16] from (*)
D2 = np.vstack([x, y, np.ones_like(x)]).T
# Forming scatter matrix [eqn. 17] from (*)
S1 = D1.T @ D1
S2 = D1.T @ D2
S3 = D2.T @ D2
# Constraint matrix [eqn. 18]
C1 = np.array([[0., 0., 2.], [0., -1., 0.], [2., 0., 0.]])
# Reduced scatter matrix [eqn. 29]
M = la.inv(C1) @ (S1 - S2 @ la.inv(S3) @ S2.T)
# M*|a b c >=l|a b c >. Find eigenvalues and eigenvectors from this
# equation [eqn. 28]
eigval, eigvec = np.linalg.eig(M)
# Eigenvector must meet constraint 4ac - b^2 to be valid.
cond = (
4*np.multiply(eigvec[0, :], eigvec[2, :])
- np.power(eigvec[1, :], 2)
)
a1 = eigvec[:, np.nonzero(cond > 0)[0]]
# |d f g> = -S3^(-1) * S2^(T)*|a b c> [eqn. 24]
a2 = la.inv(-S3) @ S2.T @ a1
# Eigenvectors |a b c d f g>
# list of the coefficients describing an ellipse [a,b,c,d,f,g]
# corresponding to ax**2 + 2bxy + cy**2 + 2dx + 2fy + g
if (a1[0] < 0): #change the signum in case < 0
a1 = -a1
a2 = -a2
self.coef_ = np.vstack([a1, a2])
return self
@property
def coefficients(self):
"""
List of the coefficients describing the fitted ellipse
Returns
-------
[a,b,c,d,f,g] corresponding to ax**2 + 2bxy + cy**2 + 2dx + 2fy + g
"""
return np.asarray(self.coef_).ravel()
def as_parameters(self):
"""Returns the definition of the fitted ellipse as localized parameters
Returns
_______
center : list
[x0, y0]
width : float
Semimajor axis
height : float
Semiminor axis
phi : float
The counterclockwise angle of rotation from the x-axis to the major
axis of the ellipse
"""
# Eigenvectors are the coefficients of an ellipse in general form
# a*x^2 + 2*b*x*y + c*y^2 + 2*d*x + 2*f*y + g = 0
# [eqn. 15) from (**) or (***)
a = self.coefficients[0]
b = self.coefficients[1] / 2.0
c = self.coefficients[2]
d = self.coefficients[3] / 2.0
f = self.coefficients[4] / 2.0
g = self.coefficients[5]
# Finding center of ellipse [eqn.19 and 20] from (**)
x0 = (c*d - b*f) / (b*b - a*c)
y0 = (a*f - b*d) / (b*b - a*c)
center = [x0, y0]
# Find the semi-axes lengths [eqn. 21 and 22] from (**)
numerator = 2.0 * (a*f*f + c*d*d + g*b*b - 2.0*b*d*f - a*c*g)
denominator1 = (b*b - a*c) * (np.sqrt((a - c)*(a - c) + 4.0*b*b) - (a + c))
denominator2 = (b*b - a*c) * (-np.sqrt((a - c)*(a - c) + 4.0*b*b) - (a + c))
width = np.sqrt(numerator / denominator1)
height = np.sqrt(numerator / denominator2)
# Angle of counterclockwise rotation of major-axis of ellipse to x-axis
# [eqn. 23] from (**) or [eqn. 26] from (***).
if (b == 0 and a < c): #calculate with the b == 0 condition
phi = 0.0
if (b == 0 and a > c):
phi = 0.5 * np.pi
if (b != 0 and a != c): #calculate with the a > c condition
if (a < c):
phi = 0.5 * np.arctan((2.0 * b) / (a - c))
if (a > c):
phi = 0.5 * np.pi + 0.5 * np.arctan((2.0 * b) / (a - c))
if (a == c): # add the case of a circle, "undefined" is the right value
phi = 0.0
return center, width, height, phi
# Add a function that shows the ellipse coefficients
def ellipse_coeff(self):
"""
List of the coefficients describing the fitted ellipse
Returns
-------
[a,b,c,d,f,g] corresponding to ax**2 + 2bxy + cy**2 + 2dx + 2fy + g
"""
a = self.coefficients[0]
b = self.coefficients[1] / 2.0
c = self.coefficients[2]
d = self.coefficients[3] / 2.0
f = self.coefficients[4] / 2.0
g = self.coefficients[5]
return a, b, c, d, f, g
def return_fit(self, n_points=None, t=None):
"""Return the X, Y values of the predicted ellipse
Points are returned along the parametric curve of the ellipse as evenly
spaced points starting at t=0 to t=2pi
Parameters
---------
n_points : int
Number of points to return
t : array
Parametric points used to generate x-y pairs, If provided,
`n_points` will be ignored
Returns
-------
X : array, shape (n_points, 2)
data values for the x-y data pairs
"""
if self.coef_ is None:
raise ValueError("Must call .fit() before using .return_fit()")
if n_points is None and t is None:
raise AttributeError("A value for `n_points` or `t` must be ",
"provided")
if t is None:
t = np.linspace(0, 2 * np.pi, n_points)
center, width, height, phi = self.as_parameters()
x = (center[0]
+ width * np.cos(t) * np.cos(phi)
- height * np.sin(t) * np.sin(phi))
y = (center[1]
+ width * np.cos(t) * np.sin(phi)
+ height * np.sin(t) * np.cos(phi))
return np.c_[x, y]