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