Define Emgu as a nuget reference for the project WPF
[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 then
26 []
27 else
28 // This is the minimum window size to check if other ellipses touch 'e'.
29 let searchRegion (e : Ellipse) =
30 {
31 KdTree.minX = e.Cx - (e.A + config.RBCRadius.Max)
32 KdTree.maxX = e.Cx + (e.A + config.RBCRadius.Max)
33 KdTree.minY = e.Cy - (e.A + config.RBCRadius.Max)
34 KdTree.maxY = e.Cy + (e.A + config.RBCRadius.Max)
35 }
36
37 // The minimum window to contain a given ellipse.
38 let ellipseWindow (e : Ellipse) =
39 let cx, cy = roundInt e.Cx, roundInt e.Cy
40 let a = int (e.A + 0.5f)
41 cx - a, cy - a, cx + a, cy + a
42
43 // Return 'true' if the point 'p' is owned by e.
44 // The lines represents all intersections with other ellipses.
45 let pixelOwnedByE (p : PointF) (e : EllipseFlaggedKd) (neighbors : (EllipseFlaggedKd * PointF * PointF) list) =
46 e.Contains p.X p.Y &&
47 seq {
48 let c = PointF(e.Cx, e.Cy)
49
50 for e', d1 in
51 (neighbors
52 |> List.choose (
53 fun (otherE, p1, p2) ->
54 if otherE.State = CellState.Removed then
55 None
56 else
57 Some (otherE, Utils.lineFromTwoPoints p1 p2)
58 )) do
59 if e'.State = e.State then // Peculiar vs peculiar or RBC vs RBC.
60 let d2 = lineFromTwoPoints c p
61 let c' = PointF(e'.Cx, e'.Cy)
62 let v = pointFromTwoLines d1 (lineFromTwoPoints c c')
63 let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c'
64 if not (Single.IsInfinity d2.A) then
65 let p' = Utils.pointFromTwoLines d1 d2
66 let delta, delta' =
67 let dx1, dx2 = (c.X - p.X), (c.X - p'.X)
68 // To avoid rounding issue.
69 if abs dx1 < 0.01f || abs dx2 < 0.01f then c.Y - p.Y, c.Y - p'.Y else dx1, dx2
70
71 // Yield 'false' when the point is owned by another ellipse.
72 if case1 then
73 yield sign delta <> sign delta' || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p
74 else
75 yield sign delta = sign delta' && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p
76 else
77 yield case1
78
79 elif e.State = CellState.Peculiar then // A peculiar always win against a RBC.
80 yield true
81 else
82 yield not <| e'.Contains p.X p.Y
83
84 } |> Seq.forall id
85
86 let ellipses = ellipses |> List.map EllipseFlaggedKd
87
88 // 1) Associate touching ellipses with each ellipses and remove ellipse with more than two intersections.
89 let tree = KdTree.Tree.BuildTree ellipses
90 let neighbors (e : EllipseFlaggedKd) : (EllipseFlaggedKd * PointF * PointF) list =
91 if e.State <> CellState.Removed then
92 tree.Search (searchRegion e)
93 // We only keep the ellipses touching 'e'.
94 |> List.choose (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 yield 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 yield 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 (fun (e, neighbors) ->
159 if e.State = CellState.Removed then
160 None
161 else
162 let mutable darkStainPixels = 0
163 let mutable nbElement = 0
164 let minX, minY, maxX, maxY = ellipseWindow e
165 for y = minY to maxY do
166 for x = minX to maxX do
167 let p = PointF(float32 x, float32 y)
168 if pixelOwnedByE p e neighbors then
169 nbElement <- nbElement + 1
170 if darkStainData.[y, x, 0] > 0uy then
171 darkStainPixels <- darkStainPixels + 1
172
173 if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement) then Some e else None)
174
175 // We do not change the state during the process to avoid to have peculiar neighbors which change the behavior of 'pixelOwnedByE'.
176 |> List.iter (fun e -> e.State <- CellState.Peculiar)
177
178 // 5) Define pixels associated to each ellipse and create the cells.
179 let diameterParasiteSquared = (2.f * config.RBCRadius.ParasiteRadius) ** 2.f |> roundInt
180 let minimumParasiteArea = config.RBCRadius.MinimumParasiteArea |> roundInt
181
182 let nucleusData = parasites.nucleus.Copy().Data // Will be modified thus the copy.
183 let parasiteData = parasites.parasite.Data
184 let darkStainData = parasites.darkStain.Data
185
186 ellipsesWithNeigbors
187 |> List.choose (
188 fun (e, neighbors) ->
189 if e.State = CellState.Removed then
190 None
191 else
192 let minX, minY, maxX, maxY = ellipseWindow e
193
194 let nucleusPixels = List<Point>()
195 let parasitePixels = List<Point>()
196
197 let mutable nbElement = 0
198
199 let elements = new Matrix<byte>(maxY - minY + 1, maxX - minX + 1)
200 for y = minY to maxY do
201 for x = minX to maxX do
202 let p = PointF(float32 x, float32 y)
203 if pixelOwnedByE p e neighbors then
204 elements.[y - minY, x - minX] <- 1uy
205 nbElement <- nbElement + 1
206
207 if nucleusData.[y, x, 0] > 0uy then
208 nucleusPixels.Add(Point(x, y))
209
210 if parasiteData.[y, x, 0] > 0uy then
211 parasitePixels.Add(Point(x, y))
212
213 let parasiteArea =
214 if nucleusPixels.Count > 0 then
215 seq {
216 for parasitePixel in parasitePixels do
217 if nucleusPixels.Exists(fun p -> pown (p.X - parasitePixel.X) 2 + pown (p.Y - parasitePixel.Y) 2 <= diameterParasiteSquared) then
218 yield 1
219 } |> Seq.sum
220 else
221 0
222
223 let cellClass =
224 if e.State = CellState.Peculiar then
225 Peculiar
226
227 elif nucleusPixels.Count > 0 && parasiteArea >= minimumParasiteArea then
228 let infectionToRemove = Morpho.connectedComponents parasites.parasite nucleusPixels
229 for p in infectionToRemove do
230 nucleusData.[p.Y, p.X, 0] <- 0uy
231 InfectedRBC
232
233 else
234 HealthyRBC
235
236 Some
237 {
238 cellClass = cellClass
239 center = Point(roundInt e.Cx, roundInt e.Cy)
240 nucleusArea = if cellClass = InfectedRBC then nucleusPixels.Count else 0
241 parasiteArea = parasiteArea
242 elements = elements
243 }
244 )