Add a way to detect the membrane of a parasite in the ring stage.
[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 let infection = parasites.infection.Copy() // To avoid to modify the parameter.
28
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 let w = img.Width
42 let w_f = float32 w
43 let h = img.Height
44 let h_f = float32 h
45
46 // Return 'true' if the point 'p' is owned by e.
47 // The lines represents all intersections with other ellipses.
48 let pixelOwnedByE (p: PointF) (e: Ellipse) (others: (Ellipse * Line) list) =
49 e.Contains p.X p.Y &&
50 seq {
51 let c = PointF(e.Cx, e.Cy)
52
53 for e', d1 in others do
54 let d2 = lineFromTwoPoints c p
55 let c' = PointF(e'.Cx, e'.Cy)
56 let v = pointFromTwoLines d1 (lineFromTwoPoints c c')
57 let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c'
58 if not (Single.IsInfinity d2.A)
59 then
60 let p' = Utils.pointFromTwoLines d1 d2
61 let delta, delta' =
62 let dx1, dx2 = (c.X - p.X), (c.X - p'.X)
63 // To avoid rounding issue.
64 if abs dx1 < 0.01f || abs dx2 < 0.01f then c.Y - p.Y, c.Y - p'.Y else dx1, dx2
65
66 // Yield 'false' when the point is owned by another ellipse.
67 if case1
68 then
69 yield sign delta <> sign delta' || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p
70 else
71 yield sign delta = sign delta' && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p
72 else
73 yield case1
74 } |> Seq.forall id
75
76 let ellipses = ellipses |> List.map EllipseFlaggedKd
77
78 // 1) Associate touching ellipses with each ellipses and remove ellipse with more than two intersections.
79 let tree = KdTree.Tree.BuildTree ellipses
80 let neighbors (e: EllipseFlaggedKd) : (EllipseFlaggedKd * PointF * PointF) list =
81 if not e.Removed
82 then
83 tree.Search (searchRegion e)
84 // We only keep the ellipses touching 'e'.
85 |> List.choose (fun otherE ->
86 if e <> otherE
87 then
88 match EEOver.EEOverlapArea e otherE with
89 | Some (_, px, _) when px.Length > 2 ->
90 otherE.Removed <- true
91 None
92 | Some (area, px, py) when area > 0.f && px.Length = 2 ->
93 Some (otherE, PointF(px.[0], py.[0]), PointF(px.[1], py.[1]))
94 | _ ->
95 None
96 else
97 None )
98 else
99 []
100
101 // We reverse the list to get the lower score ellipses first.
102 let ellipsesWithNeigbors = ellipses |> List.map (fun e -> e, neighbors e) |> List.rev
103
104 // 2) Remove ellipses touching the edges.
105 for e in ellipses do
106 if e.isOutside w_f h_f then e.Removed <- true
107
108 // 3) Remove ellipses with a high standard deviation (high contrast).
109 let imgData = img.Data
110 let globalStdDeviation = MathNet.Numerics.Statistics.Statistics.PopulationStandardDeviation(seq {
111 for y in 0 .. h - 1 do
112 for x in 0 .. w - 1 do
113 yield float imgData.[y, x, 0] })
114
115 for e in ellipses do
116 if not e.Removed
117 then
118 let shrinkedE = e.Scale 0.9f
119 let minX, minY, maxX, maxY = ellipseWindow shrinkedE
120
121 let stdDeviation = MathNet.Numerics.Statistics.Statistics.StandardDeviation (seq {
122 for y in (if minY < 0 then 0 else minY) .. (if maxY >= h then h - 1 else maxY) do
123 for x in (if minX < 0 then 0 else minX) .. (if maxX >= w then w - 1 else maxX) do
124 if shrinkedE.Contains (float32 x) (float32 y)
125 then
126 yield float imgData.[y, x, 0] })
127
128 if stdDeviation > globalStdDeviation * config.Parameters.standardDeviationMaxRatio then
129 e.Removed <- true
130
131 // 4) Remove ellipses with little area.
132 let minArea = config.RBCRadius.MinArea
133 for e, neighbors in ellipsesWithNeigbors do
134 if not e.Removed
135 then
136 let minX, minY, maxX, maxY = ellipseWindow e
137
138 let mutable area = 0
139 for y in (if minY < 0 then 0 else minY) .. (if maxY >= h then h - 1 else maxY) do
140 for x in (if minX < 0 then 0 else minX) .. (if maxX >= w then w - 1 else maxX) do
141 let p = PointF(float32 x, float32 y)
142 if pixelOwnedByE p e (neighbors |> List.choose (fun (otherE, p1, p2) -> if otherE.Removed then None else Some (otherE :> Ellipse, Utils.lineFromTwoPoints p1 p2)))
143 then
144 area <- area + 1
145
146 if area < int minArea
147 then
148 e.Removed <- true
149
150 // 5) Define pixels associated to each ellipse and create the cells.
151 let radiusParasiteRatio = 0.4f
152 let radiusParasite = config.RBCRadius.Pixel * 0.5f
153 let perimeterParasiteSquared = (2.f * radiusParasite) ** 2.f |> roundInt
154 let parasiteOccupation = 0.08f // 8 %
155 let minimumParasiteArea = Const.PI * radiusParasite ** 2.f * parasiteOccupation |> roundInt
156 //let minimumStainArea = roundInt <| config.RBCRadius.Area * 0.02f // 1.5 %
157 ellipsesWithNeigbors
158 |> List.choose (fun (e, neighbors) ->
159 if e.Removed
160 then
161 None
162 else
163 let minX, minY, maxX, maxY = ellipseWindow e
164
165 let infectedPixels = List<Point>()
166 let stainPixels = List<Point>()
167
168 //let mutable stainPixels = 0
169 let mutable darkStainPixels = 0
170 let mutable nbElement = 0
171
172 let elements = new Matrix<byte>(maxY - minY + 1, maxX - minX + 1)
173 for y in minY .. maxY do
174 for x in minX .. maxX do
175 let p = PointF(float32 x, float32 y)
176 if pixelOwnedByE p e (neighbors |> List.choose (fun (otherE, p1, p2) -> if otherE.Removed then None else Some (otherE :> Ellipse, Utils.lineFromTwoPoints p1 p2)))
177 then
178 elements.[y-minY, x-minX] <- 1uy
179 nbElement <- nbElement + 1
180
181 let infected = infection.Data.[y, x, 0] > 0uy
182 let stain = parasites.stain.Data.[y, x, 0] > 0uy
183 let darkStain = parasites.darkStain.Data.[y, x, 0] > 0uy
184
185 if infected
186 then
187 infectedPixels.Add(Point(x, y))
188
189 if stain
190 then
191 stainPixels.Add(Point(x, y))
192
193 if darkStain
194 then
195 darkStainPixels <- darkStainPixels + 1
196
197 let mutable stainArea = 0
198 if infectedPixels.Count > 0
199 then
200 for stainPixel in stainPixels do
201 if infectedPixels.Exists(fun p -> pown (p.X - stainPixel.X) 2 + pown (p.Y - stainPixel.Y) 2 <= perimeterParasiteSquared)
202 then
203 stainArea <- stainArea + 1
204
205
206 let cellClass =
207 if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement)
208 //|| float stainPixels > config.Parameters.maxStainRatio * (float nbElement)
209 then
210 Peculiar
211
212 elif infectedPixels.Count > 0 && stainArea >= minimumParasiteArea
213 then
214 let infectionToRemove = ImgTools.connectedComponents parasites.stain infectedPixels
215 for p in infectionToRemove do
216 infection.Data.[p.Y, p.X, 0] <- 0uy
217 InfectedRBC
218
219 else
220 HealthyRBC
221
222 Some { cellClass = cellClass
223 center = Point(roundInt e.Cx, roundInt e.Cy)
224 infectedArea = if cellClass = InfectedRBC then infectedPixels.Count else 0
225 stainArea = stainArea
226 elements = elements })