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