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