Cleaning, micro-optimizations.
[master-thesis.git] / Parasitemia / Parasitemia / Classifier.fs
1 module 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.RBCMaxRadius)
33 KdTree.maxX = e.Cx + (e.A + config.RBCMaxRadius)
34 KdTree.minY = e.Cy - (e.A + config.RBCMaxRadius)
35 KdTree.maxY = e.Cy + (e.A + config.RBCMaxRadius) }
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.5)
41 cx - a, cy - a, cx + a, cy + a
42
43 let w = img.Width
44 let w_f = float w
45 let h = img.Height
46 let h_f = float 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: PointD) (e: Ellipse) (others: (Ellipse * Line) list) =
51 e.Contains p.X p.Y &&
52 seq {
53 let c = PointD(e.Cx, e.Cy)
54 for e', d1 in others do
55 let d2 = Utils.lineFromTwoPoints c p
56 let c' = PointD(e'.Cx, e'.Cy)
57 let v = pointFromTwoLines d1 (lineFromTwoPoints c c')
58 let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c'
59 if d2.Valid
60 then
61 let p' = Utils.pointFromTwoLines d1 d2
62 // Yield 'false' when the point is owned by another ellipse.
63 if case1
64 then
65 yield sign (c.X - p.X) <> sign (c.X - p'.X) || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p
66 else
67 yield sign (c.X - p.X) = sign (c.X - p'.X) && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p
68 else
69 yield case1
70 } |> Seq.forall id
71
72 let ellipses = ellipses |> List.map EllipseFlaggedKd
73
74 // 1) Associate touching ellipses with each ellipses and remove ellipse with more than two intersections.
75 let tree = KdTree.Tree.BuildTree ellipses
76 let neighbors (e: EllipseFlaggedKd) : (EllipseFlaggedKd * PointD * PointD) list =
77 if not e.Removed
78 then
79 tree.Search (searchRegion e)
80 // We only keep the ellipses touching 'e'.
81 |> List.choose (fun otherE ->
82 match EEOver.EEOverlapArea e otherE with
83 | Some (_, px, _) when px.Length > 2 ->
84 otherE.Removed <- true
85 None
86 | Some (area, px, py) when area > 0.0 && px.Length = 2 ->
87 Some (otherE, PointD(px.[0], py.[0]), PointD(px.[1], py.[1]))
88 | _ ->
89 None )
90 else
91 []
92
93 // We reverse the list to get the lower score ellipses first.
94 let ellipsesWithNeigbors = ellipses |> List.map (fun e -> e, neighbors e) |> List.rev
95
96
97 // 2) Remove ellipses touching the edges.
98 for e in ellipses do
99 if e.isOutside w_f h_f then e.Removed <- true
100
101 // 3) Remove ellipses with a high standard deviation (high contrast).
102
103 // CvInvoke.Normalize(img, img, 0.0, 255.0, CvEnum.NormType.MinMax) // Not needed.
104
105 let globalStdDeviation = MathNet.Numerics.Statistics.Statistics.StandardDeviation(seq {
106 for y in 0 .. h - 1 do
107 for x in 0 .. w - 1 do
108 yield float img.Data.[y, x, 0] })
109
110 for e in ellipses do
111 if not e.Removed
112 then
113 let shrinkedE = e.Scale 0.9
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 (float x) (float y)
120 then
121 yield float img.Data.[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.RBCMinArea
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 >= h then h - 1 else maxY) do
135 for x in (if minX < 0 then 0 else minX) .. (if maxX >= w then w - 1 else maxX) do
136 let p = PointD(float x, float 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 ellipsesWithNeigbors
147 |> List.choose (fun (e, neighbors) ->
148 if e.Removed
149 then
150 None
151 else
152 let minX, minY, maxX, maxY = ellipseWindow e
153
154 let infectedPixels = List<Point>()
155 let mutable stainPixels = 0
156 let mutable darkStainPixels = 0
157 let mutable nbElement = 0
158
159 let elements = new Matrix<byte>(maxY - minY + 1, maxX - minX + 1)
160 for y in minY .. maxY do
161 for x in minX .. maxX do
162 let p = PointD(float x, float y)
163 if pixelOwnedByE p e (neighbors |> List.choose (fun (otherE, p1, p2) -> if otherE.Removed then None else Some (otherE :> Ellipse, Utils.lineFromTwoPoints p1 p2)))
164 then
165 elements.[y-minY, x-minX] <- 1uy
166 nbElement <- nbElement + 1
167
168 if infection.Data.[y, x, 0] > 0uy
169 then
170 infectedPixels.Add(Point(x, y))
171
172 if parasites.stain.Data.[y, x, 0] > 0uy
173 then
174 stainPixels <- stainPixels + 1
175
176 if parasites.darkStain.Data.[y, x, 0] > 0uy
177 then
178 darkStainPixels <- darkStainPixels + 1
179
180 let cellClass =
181 if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement) ||
182 float stainPixels > config.Parameters.maxStainRatio * (float nbElement) (* ||
183 sqrt (((float sumCoords_x) / (float nbElement) - e.Cx) ** 2.0 + ((float sumCoords_y) / (float nbElement) - e.Cy) ** 2.0) > e.A * config.maxOffcenter *)
184 then
185 Peculiar
186 elif infectedPixels.Count >= 1
187 then
188 let infectionToRemove = ImgTools.connectedComponents parasites.stain infectedPixels
189 for p in infectionToRemove do
190 infection.Data.[p.Y, p.X, 0] <- 0uy
191 InfectedRBC
192 else
193 HealthyRBC
194
195 Some { cellClass = cellClass
196 center = Point(roundInt e.Cx, roundInt e.Cy)
197 elements = elements })