To .NET 5 (lot of refactoring)
[master-thesis.git] / Parasitemia / ParasitemiaCore / Classifier.fs
1 module ParasitemiaCore.Classifier
2
3 open System
4 open System.Collections.Generic
5 open System.Drawing
6
7 open Emgu.CV
8
9 open Types
10 open Utils
11
12 type CellState = RBC = 1 | Removed = 2 | Peculiar = 3
13
14 type private EllipseFlaggedKd (e : Ellipse) =
15 inherit Ellipse (e.Cx, e.Cy, e.A, e.B, e.Alpha)
16
17 member val State = CellState.RBC with get, set
18
19 interface KdTree.I2DCoords with
20 member this.X = this.Cx
21 member this.Y = this.Cy
22
23 let findCells (ellipses : Ellipse list) (parasites : ParasitesMarker.Result) (width : int) (height : int) (config : Config.Config) : Cell list =
24 if ellipses.IsEmpty then
25 []
26 else
27 // This is the minimum window size to check if other ellipses touch 'e'.
28 let searchRegion (e : Ellipse) =
29 {
30 KdTree.minX = e.Cx - (e.A + config.RBCRadius.Max)
31 KdTree.maxX = e.Cx + (e.A + config.RBCRadius.Max)
32 KdTree.minY = e.Cy - (e.A + config.RBCRadius.Max)
33 KdTree.maxY = e.Cy + (e.A + config.RBCRadius.Max)
34 }
35
36 // The minimum window to contain a given ellipse.
37 let ellipseWindow (e : Ellipse) =
38 let cx, cy = roundInt e.Cx, roundInt e.Cy
39 let a = int (e.A + 0.5f)
40 cx - a, cy - a, cx + a, cy + a
41
42 // Return 'true' if the point 'p' is owned by e.
43 // The lines represents all intersections with other ellipses.
44 let pixelOwnedByE (p : PointF) (e : EllipseFlaggedKd) (neighbors : (EllipseFlaggedKd * PointF * PointF) list) =
45 e.Contains p.X p.Y &&
46 seq {
47 let c = PointF (e.Cx, e.Cy)
48
49 for e', d1 in
50 (neighbors
51 |> List.choose (
52 fun (otherE, p1, p2) ->
53 if otherE.State = CellState.Removed then
54 None
55 else
56 Some (otherE, Utils.lineFromTwoPoints p1 p2)
57 )) do
58 if e'.State = e.State then // Peculiar vs peculiar or RBC vs RBC.
59 let d2 = lineFromTwoPoints c p
60 let c' = PointF (e'.Cx, e'.Cy)
61 let v = pointFromTwoLines d1 (lineFromTwoPoints c c')
62 let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c'
63 if not (Single.IsInfinity d2.A) then
64 let p' = Utils.pointFromTwoLines d1 d2
65 let delta, delta' =
66 let dx1, dx2 = (c.X - p.X), (c.X - p'.X)
67 // To avoid rounding issue.
68 if abs dx1 < 0.01f || abs dx2 < 0.01f then c.Y - p.Y, c.Y - p'.Y else dx1, dx2
69
70 // Yield 'false' when the point is owned by another ellipse.
71 if case1 then
72 sign delta <> sign delta' || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p
73 else
74 sign delta = sign delta' && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p
75 else
76 case1
77
78 elif e.State = CellState.Peculiar then // A peculiar always win against a RBC.
79 true
80 else
81 not <| e'.Contains p.X p.Y
82
83 } |> Seq.forall id
84
85 let ellipses = ellipses |> List.map EllipseFlaggedKd
86
87 // 1) Associate touching ellipses with each ellipses and remove ellipse with more than two intersections.
88 let tree = KdTree.Tree.BuildTree ellipses
89 let neighbors (e : EllipseFlaggedKd) : (EllipseFlaggedKd * PointF * PointF) list =
90 if e.State <> CellState.Removed then
91 tree.Search (searchRegion e)
92 // We only keep the ellipses touching 'e'.
93 |> List.choose (
94 fun otherE ->
95 if e <> otherE then
96 match EEOver.EEOverlapArea e otherE with
97 | Some (_, px, _) when px.Length > 2 ->
98 otherE.State <- CellState.Removed
99 None
100 | Some (area, px, py) when area > 0.f && px.Length = 2 ->
101 Some (otherE, PointF (px.[0], py.[0]), PointF (px.[1], py.[1]))
102 | _ ->
103 None
104 else
105 None
106 )
107 else
108 []
109
110 let ellipsesWithNeigbors = ellipses |> List.map (fun e -> e, neighbors e)
111
112 // 2) Remove ellipses touching the edges.
113 let widthF, heightF = float32 width, float32 height
114 for e in ellipses do
115 if e.IsOutside widthF heightF then e.State <- CellState.Removed
116
117 // 3) Remove ellipses with a high standard deviation (high contrast).
118 // Obsolete. It was useful when the ellipses result quality wasn't good.
119 (* let imgData = img.Data
120 let globalStdDeviation = MathNet.Numerics.Statistics.Statistics.PopulationStandardDeviation (seq {
121 for y in 0 .. h - 1 do
122 for x in 0 .. w - 1 do
123 float imgData.[y, x, 0] })
124
125 for e in ellipses do
126 if not e.Removed then
127 let shrinkedE = e.Scale 0.9f
128 let minX, minY, maxX, maxY = ellipseWindow shrinkedE
129
130 let stdDeviation = MathNet.Numerics.Statistics.Statistics.StandardDeviation (seq {
131 for y in (if minY < 0 then 0 else minY) .. (if maxY >= h then h - 1 else maxY) do
132 for x in (if minX < 0 then 0 else minX) .. (if maxX >= w then w - 1 else maxX) do
133 if shrinkedE.Contains (float32 x) (float32 y) then
134 float imgData.[y, x, 0] })
135
136 if stdDeviation > globalStdDeviation * config.Parameters.standardDeviationMaxRatio then
137 e.Removed <- true *)
138
139 // 4) Remove ellipses with little area.
140 let minArea = config.RBCRadius.MinArea
141 for e, neighbors in ellipsesWithNeigbors do
142 if e.State <> CellState.Removed then
143 let minX, minY, maxX, maxY = ellipseWindow e
144
145 let mutable area = 0
146 for y = (if minY < 0 then 0 else minY) to (if maxY >= height then height - 1 else maxY) do
147 for x = (if minX < 0 then 0 else minX) to (if maxX >= width then width - 1 else maxX) do
148 let p = PointF (float32 x, float32 y)
149 if pixelOwnedByE p e neighbors then
150 area <- area + 1
151
152 if area < int minArea then
153 e.State <- CellState.Removed
154
155 // 5) Define non-rbc (peculiar) cells.
156 let darkStainData = parasites.darkStain.Data
157 ellipsesWithNeigbors
158 |> List.choose (
159 fun (e, neighbors) ->
160 if e.State = CellState.Removed then
161 None
162 else
163 let mutable darkStainPixels = 0
164 let mutable nbElement = 0
165 let minX, minY, maxX, maxY = ellipseWindow e
166 for y = minY to maxY do
167 for x = minX to maxX do
168 let p = PointF (float32 x, float32 y)
169 if pixelOwnedByE p e neighbors then
170 nbElement <- nbElement + 1
171 if darkStainData.[y, x, 0] > 0uy then
172 darkStainPixels <- darkStainPixels + 1
173
174 if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement) then Some e else None
175 )
176
177 // We do not change the state during the process to avoid to have peculiar neighbors which change the behavior of 'pixelOwnedByE'.
178 |> List.iter (fun e -> e.State <- CellState.Peculiar)
179
180 // 5) Define pixels associated to each ellipse and create the cells.
181 let diameterParasiteSquared = (2.f * config.RBCRadius.ParasiteRadius) ** 2.f |> roundInt
182 let minimumParasiteArea = config.RBCRadius.MinimumParasiteArea |> roundInt
183
184 let nucleusData = parasites.nucleus.Copy().Data // Will be modified thus the copy.
185 let parasiteData = parasites.parasite.Data
186 let darkStainData = parasites.darkStain.Data
187
188 ellipsesWithNeigbors
189 |> List.choose (
190 fun (e, neighbors) ->
191 if e.State = CellState.Removed then
192 None
193 else
194 let minX, minY, maxX, maxY = ellipseWindow e
195
196 let nucleusPixels = List<Point> ()
197 let parasitePixels = List<Point> ()
198
199 let mutable nbElement = 0
200
201 let elements = new Matrix<byte> (maxY - minY + 1, maxX - minX + 1)
202 for y = minY to maxY do
203 for x = minX to maxX do
204 let p = PointF (float32 x, float32 y)
205 if pixelOwnedByE p e neighbors then
206 elements.[y - minY, x - minX] <- 1uy
207 nbElement <- nbElement + 1
208
209 if nucleusData.[y, x, 0] > 0uy then
210 nucleusPixels.Add (Point (x, y))
211
212 if parasiteData.[y, x, 0] > 0uy then
213 parasitePixels.Add (Point (x, y))
214
215 let parasiteArea =
216 if nucleusPixels.Count > 0 then
217 seq {
218 for parasitePixel in parasitePixels do
219 if nucleusPixels.Exists (fun p -> pown (p.X - parasitePixel.X) 2 + pown (p.Y - parasitePixel.Y) 2 <= diameterParasiteSquared) then
220 1
221 } |> Seq.sum
222 else
223 0
224
225 let cellClass =
226 if e.State = CellState.Peculiar then
227 Peculiar
228
229 elif nucleusPixels.Count > 0 && parasiteArea >= minimumParasiteArea then
230 let infectionToRemove = Morpho.connectedComponents parasites.parasite nucleusPixels
231 for p in infectionToRemove do
232 nucleusData.[p.Y, p.X, 0] <- 0uy
233 InfectedRBC
234
235 else
236 HealthyRBC
237
238 Some
239 {
240 cellClass = cellClass
241 center = Point (roundInt e.Cx, roundInt e.Cy)
242 nucleusArea = if cellClass = InfectedRBC then nucleusPixels.Count else 0
243 parasiteArea = parasiteArea
244 elements = elements
245 }
246 )