4e4823024e18bc4317c9c6413b8dd706a76597a1
[master-thesis.git] / Parasitemia / ParasitemiaCore / Ellipse.fs
1 module ParasitemiaCore.Ellipse
2
3 open System
4 open System.Collections.Generic
5 open System.Drawing
6
7 open MathNet.Numerics.LinearAlgebra
8
9 open Emgu.CV
10 open Emgu.CV.Structure
11
12 open Utils
13 open Config
14 open MatchingEllipses
15 open Const
16
17 /// <summary>
18 /// Try to build an ellipse from three points and two tangents passing by the first and the second point.
19 /// 'Ellipse.A' is always equal or greater than Ellipse.B.
20 /// 'Ellipse.Alpha' is between 0 and Pi.
21 /// </summary>
22 let ellipse (p1x: float) (p1y: float) (m1: float) (p2x: float) (p2y: float) (m2: float) (p3x: float) (p3y: float) : Types.Ellipse option =
23 let p0 = pointFromTwoLines (Types.Line(float32 m1, float32 (p1y - m1 * p1x))) (Types.Line(float32 m2, float32(p2y - m2 * p2x)))
24 let p0x, p0y = float p0.X, float p0.Y
25
26 let s = matrix [[ 1.; 0.; 0. ]
27 [ 0.; 0.; -0.5 ]
28 [ 0.; -0.5; 0. ]]
29
30 let v0 = matrix [[ 1.; p0x; p0y ]]
31 let v1 = matrix [[ 1.; p1x; p1y ]]
32 let v2 = matrix [[ 1.; p2x; p2y ]]
33 let v3 = matrix [[ 1.; p3x; p3y ]]
34
35 let p = (v3.Stack(v1).Stack(v2).Determinant() * v0).Stack(v0.Stack(v3).Stack(v2).Determinant() * v1).Stack(v0.Stack(v1).Stack(v3).Determinant() * v2).Transpose()
36 let conicMat = p * s.Inverse() * p.Transpose()
37 let a = conicMat.[0, 0]
38 let b = conicMat.[0, 1]
39 let c = conicMat.[1, 1]
40 let d = conicMat.[0, 2]
41 let e = conicMat.[1, 2]
42 let f = conicMat.[2, 2]
43
44 // Center.
45 let cx = b / a
46 let cy = d / a
47
48 let at = c * f - e ** 2. + (e * d - b * f) * cx + (b * e - c * d) * cy
49 if at = 0.
50 then
51 None
52 else
53 let q = (-1. / at) * (matrix [[ a * f - d ** 2.0; b * d - a * e ]; [ b * d - a * e; a * c - b ** 2.0 ]])
54 let eigen = q.Evd()
55 let eigenValues = eigen.EigenValues
56 let lambda = eigenValues.[1].Real
57 let mu = eigenValues.[0].Real
58
59 if lambda <= 0. || mu <= 0.
60 then
61 None
62 else
63 let r1, r2 = 1. / (sqrt lambda), 1. / (sqrt mu)
64
65 let eigenVectors = eigen.EigenVectors
66 let v_a = eigenVectors.[0, 0]
67 let v_b = eigenVectors.[1, 0] // [0, 1]
68
69 // Angle against the longest axis.
70 let phi = (if r2 > r1 then atan (v_b / v_a) else atan (v_a / v_b))
71
72 let phi' = if phi < 0. then phi + Math.PI else phi
73 let majorAxis, minorAxis = if r1 > r2 then r1, r2 else r2, r1
74
75 Some (Types.Ellipse(float32 cx, float32 cy, float32 majorAxis, float32 minorAxis, float32 phi'))
76
77
78 let private vectorRotation (p1x: float32) (p1y: float32) (v1x: float32) (v1y: float32) (px: float32) (py: float32) : float32 =
79 let mutable rotation = 1.f
80 if p1y > py
81 then
82 if v1x > 0.f
83 then
84 rotation <- -1.f
85 elif p1y < py
86 then
87 if v1x < 0.f
88 then
89 rotation <- -1.f
90 elif p1x > px
91 then
92 if v1y < 0.f
93 then
94 rotation <- -1.f
95 elif p1x < px
96 then
97 if v1y > 0.f
98 then
99 rotation <- -1.f
100 rotation
101
102 let private areVectorsValid (p1x: float32) (p1y: float32) (p2x: float32) (p2y: float32) (v1x: float32) (v1y: float32) (v2x: float32) (v2y: float32) : (float32 * float32) option =
103 let m1 = -v1x / v1y
104 let m2 = -v2x / v2y
105
106 let b1 = -m1 * p1x + p1y
107 let b2 = -m2 * p2x + p2y
108 let px = -((b1 - b2) / (m1 - m2))
109 let py = -((m2 * b1 - m1 * b2) / (m1 - m2))
110
111 let rot1 = vectorRotation p1x p1y v1x v1y px py
112 let rot2 = vectorRotation p2x p2y v2x v2y px py
113
114 if rot1 = rot2
115 then
116 None
117 else
118 let alpha1 = atan2 (p1y - py) (p1x - px)
119 let alpha2 = atan2 (p2y - py) (p2x - px)
120
121 let alpha1' = if alpha1 < 0.f then 2.f * PI + alpha1 else alpha1
122 let alpha2' = if alpha2 < 0.f then 2.f * PI + alpha2 else alpha2
123
124 let diff = rot1 * alpha1' + rot2 * alpha2'
125
126 if diff > PI || (diff < 0.f && diff > -PI)
127 then
128 None
129 else
130 Some (m1, m2)
131
132 let find (edges: Matrix<byte>)
133 (xGradient: Matrix<float32>)
134 (yGradient: Matrix<float32>)
135 (config: Config) : MatchingEllipses =
136
137 let r1, r2 = config.RBCRadius.Min, config.RBCRadius.Max
138 let incrementWindowDivisor = 4.f
139
140 // We choose a window size for which the biggest ellipse can always be fitted in.
141 let windowSize = roundInt (2.f * r2)
142 let factorNbPick = config.Parameters.factorNbPick
143
144 let increment = windowSize / (int incrementWindowDivisor)
145
146 let radiusTolerance = (r2 - r1) * 0.2f
147
148 let squaredMinimumDistance = (float r2 / 1.5) ** 2.
149 let inline squaredDistance x1 y1 x2 y2 = (x1 - x2) ** 2. + (y1 - y2) ** 2.
150
151 let h = edges.Height
152 let w = edges.Width
153 let h_f = float32 h
154 let w_f = float32 w
155
156 let mutable last_i, last_j = Int32.MaxValue, Int32.MaxValue
157
158 let currentElements = List<Point>()
159
160 let edgesData = edges.Data
161 let xDirData = xGradient.Data
162 let yDirData = yGradient.Data
163
164 let rng = Random(42)
165
166 let ellipses = MatchingEllipses(config.RBCRadius.Pixel)
167
168 for window_i in -windowSize + increment .. increment .. h - increment do
169 for window_j in -windowSize + increment .. increment .. w - increment do
170
171 let window_i_begin = if window_i < 0 then 0 else window_i
172 let window_i_end = if window_i + windowSize - 1 >= h then h - 1 else window_i + windowSize - 1
173 let window_j_begin = if window_j < 0 then 0 else window_j
174 let window_j_end = if window_j + windowSize - 1 >= w then w - 1 else window_j + windowSize - 1
175
176 // Remove old elements.
177 let indexFirstElement = currentElements.FindIndex(fun p -> p.X >= window_j_begin)
178 if indexFirstElement > 0
179 then currentElements.RemoveRange(0, indexFirstElement)
180
181 // Add the new elements.
182 let newElemsBegin_j = window_j + windowSize - increment
183 let newElemsEnd_j = window_j + windowSize - 1
184 for j in (if newElemsBegin_j < 0 then 0 else newElemsBegin_j) .. (if newElemsEnd_j >= w then w - 1 else newElemsEnd_j) do
185 for i in window_i_begin .. window_i_end do
186 if edgesData.[i, j] = 1uy
187 then currentElements.Add(Point(j, i))
188
189 if currentElements.Count >= 10
190 then
191 let mutable nbOfPicks = (float currentElements.Count) * factorNbPick |> int
192 while nbOfPicks > 0 do
193 let p1 = currentElements.[rng.Next(currentElements.Count)]
194 let p2 = currentElements.[rng.Next(currentElements.Count)]
195 let p3 = currentElements.[rng.Next(currentElements.Count)]
196 if p1 <> p2 && p1 <> p3 && p2 <> p3
197 then
198 nbOfPicks <- nbOfPicks - 1
199 let p1yf, p1xf = float p1.Y, float p1.X
200 let p2yf, p2xf = float p2.Y, float p2.X
201 let p3yf, p3xf = float p3.Y, float p3.X
202 if squaredDistance p1xf p1yf p2xf p2yf >= squaredMinimumDistance &&
203 squaredDistance p1xf p1yf p3xf p3yf >= squaredMinimumDistance &&
204 squaredDistance p2xf p2yf p3xf p3yf >= squaredMinimumDistance
205 then
206 match areVectorsValid (float32 p1xf) (float32 p1yf) (float32 p2xf) (float32 p2yf) -xDirData.[p1.Y, p1.X] -yDirData.[p1.Y, p1.X] -xDirData.[p2.Y, p2.X] -yDirData.[p2.Y, p2.X] with
207 | Some (m1, m2) ->
208 match ellipse p1xf p1yf (float m1) p2xf p2yf (float m2) p3xf p3yf with
209 | Some e when e.Cx > 0.f && e.Cx < w_f - 1.f && e.Cy > 0.f && e.Cy < h_f - 1.f &&
210 e.A >= r1 - radiusTolerance && e.A <= r2 + radiusTolerance && e.B >= r1 - radiusTolerance && e.B <= r2 + radiusTolerance ->
211 ellipses.Add e
212 | _ -> ()
213 | _ -> ()
214
215 currentElements.Clear()
216
217 ellipses
218