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