Remove the removing of cells bases on standard deviation.
[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) (width: int) (height: int) (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 // Return 'true' if the point 'p' is owned by e.
40 // The lines represents all intersections with other ellipses.
41 let pixelOwnedByE (p: PointF) (e: Ellipse) (others: (Ellipse * Line) list) =
42 e.Contains p.X p.Y &&
43 seq {
44 let c = PointF(e.Cx, e.Cy)
45
46 for e', d1 in others do
47 let d2 = lineFromTwoPoints c p
48 let c' = PointF(e'.Cx, e'.Cy)
49 let v = pointFromTwoLines d1 (lineFromTwoPoints c c')
50 let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c'
51 if not (Single.IsInfinity d2.A)
52 then
53 let p' = Utils.pointFromTwoLines d1 d2
54 let delta, delta' =
55 let dx1, dx2 = (c.X - p.X), (c.X - p'.X)
56 // To avoid rounding issue.
57 if abs dx1 < 0.01f || abs dx2 < 0.01f then c.Y - p.Y, c.Y - p'.Y else dx1, dx2
58
59 // Yield 'false' when the point is owned by another ellipse.
60 if case1
61 then
62 yield sign delta <> sign delta' || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p
63 else
64 yield sign delta = sign delta' && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p
65 else
66 yield case1
67 } |> Seq.forall id
68
69 let ellipses = ellipses |> List.map EllipseFlaggedKd
70
71 // 1) Associate touching ellipses with each ellipses and remove ellipse with more than two intersections.
72 let tree = KdTree.Tree.BuildTree ellipses
73 let neighbors (e: EllipseFlaggedKd) : (EllipseFlaggedKd * PointF * PointF) list =
74 if not e.Removed
75 then
76 tree.Search (searchRegion e)
77 // We only keep the ellipses touching 'e'.
78 |> List.choose (fun otherE ->
79 if e <> otherE
80 then
81 match EEOver.EEOverlapArea e otherE with
82 | Some (_, px, _) when px.Length > 2 ->
83 otherE.Removed <- true
84 None
85 | Some (area, px, py) when area > 0.f && px.Length = 2 ->
86 Some (otherE, PointF(px.[0], py.[0]), PointF(px.[1], py.[1]))
87 | _ ->
88 None
89 else
90 None )
91 else
92 []
93
94 // We reverse the list to get the lower score ellipses first.
95 let ellipsesWithNeigbors = ellipses |> List.map (fun e -> e, neighbors e) |> List.rev
96
97 // 2) Remove ellipses touching the edges.
98 let widthF, heightF = float32 width, float32 height
99 for e in ellipses do
100 if e.isOutside widthF heightF then e.Removed <- true
101
102 // 3) Remove ellipses with a high standard deviation (high contrast).
103 // Obsolete. It was useful when the ellipses result quality wasn't good.
104 (* let imgData = img.Data
105 let globalStdDeviation = MathNet.Numerics.Statistics.Statistics.PopulationStandardDeviation(seq {
106 for y in 0 .. h - 1 do
107 for x in 0 .. w - 1 do
108 yield float imgData.[y, x, 0] })
109
110 for e in ellipses do
111 if not e.Removed
112 then
113 let shrinkedE = e.Scale 0.9f
114 let minX, minY, maxX, maxY = ellipseWindow shrinkedE
115
116 let stdDeviation = MathNet.Numerics.Statistics.Statistics.StandardDeviation (seq {
117 for y in (if minY < 0 then 0 else minY) .. (if maxY >= h then h - 1 else maxY) do
118 for x in (if minX < 0 then 0 else minX) .. (if maxX >= w then w - 1 else maxX) do
119 if shrinkedE.Contains (float32 x) (float32 y)
120 then
121 yield float imgData.[y, x, 0] })
122
123 if stdDeviation > globalStdDeviation * config.Parameters.standardDeviationMaxRatio then
124 e.Removed <- true *)
125
126 // 4) Remove ellipses with little area.
127 let minArea = config.RBCRadius.MinArea
128 for e, neighbors in ellipsesWithNeigbors do
129 if not e.Removed
130 then
131 let minX, minY, maxX, maxY = ellipseWindow e
132
133 let mutable area = 0
134 for y in (if minY < 0 then 0 else minY) .. (if maxY >= height then height - 1 else maxY) do
135 for x in (if minX < 0 then 0 else minX) .. (if maxX >= width then width - 1 else maxX) do
136 let p = PointF(float32 x, float32 y)
137 if pixelOwnedByE p e (neighbors |> List.choose (fun (otherE, p1, p2) -> if otherE.Removed then None else Some (otherE :> Ellipse, Utils.lineFromTwoPoints p1 p2)))
138 then
139 area <- area + 1
140
141 if area < int minArea
142 then
143 e.Removed <- true
144
145 // 5) Define pixels associated to each ellipse and create the cells.
146 let diameterParasiteSquared = (2.f * config.RBCRadius.ParasiteRadius) ** 2.f |> roundInt
147 let minimumParasiteArea = config.RBCRadius.MinimumParasiteArea |> roundInt
148
149 let nucleusData = parasites.nucleus.Copy().Data // Will be modified thus the copy.
150 let parasiteData = parasites.parasite.Data
151 let darkStainData = parasites.darkStain.Data
152
153 ellipsesWithNeigbors
154 |> List.choose (fun (e, neighbors) ->
155 if e.Removed
156 then
157 None
158 else
159 let minX, minY, maxX, maxY = ellipseWindow e
160
161 let nucleusPixels = List<Point>()
162 let parasitePixels = List<Point>()
163
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 nucleusData.[y, x, 0] > 0uy
177 then
178 nucleusPixels.Add(Point(x, y))
179
180 if parasiteData.[y, x, 0] > 0uy
181 then
182 parasitePixels.Add(Point(x, y))
183
184 if darkStainData.[y, x, 0] > 0uy
185 then
186 darkStainPixels <- darkStainPixels + 1
187
188 let mutable parasiteArea = 0
189 if nucleusPixels.Count > 0
190 then
191 for parasitePixel in parasitePixels do
192 if nucleusPixels.Exists(fun p -> pown (p.X - parasitePixel.X) 2 + pown (p.Y - parasitePixel.Y) 2 <= diameterParasiteSquared)
193 then
194 parasiteArea <- parasiteArea + 1
195
196 let cellClass =
197 if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement)
198 then
199 Peculiar
200
201 elif nucleusPixels.Count > 0 && parasiteArea >= minimumParasiteArea
202 then
203 let infectionToRemove = Morpho.connectedComponents parasites.parasite nucleusPixels
204 for p in infectionToRemove do
205 nucleusData.[p.Y, p.X, 0] <- 0uy
206 InfectedRBC
207
208 else
209 HealthyRBC
210
211 Some { cellClass = cellClass
212 center = Point(roundInt e.Cx, roundInt e.Cy)
213 nucleusArea = if cellClass = InfectedRBC then nucleusPixels.Count else 0
214 parasiteArea = parasiteArea
215 elements = elements })