Update coding style.
[master-thesis.git] / Parasitemia / ParasitemiaCore / Classifier.fs
index 479ba59..9b247f4 100644 (file)
@@ -10,197 +10,238 @@ open Emgu.CV.Structure
 open Types
 open Utils
 
+type CellState = RBC = 1 | Removed = 2 | Peculiar = 3
 
-type private EllipseFlaggedKd (e: Ellipse) =
+type private EllipseFlaggedKd (e : Ellipse) =
     inherit Ellipse (e.Cx, e.Cy, e.A, e.B, e.Alpha)
 
-    member val Removed = false with get, set
+    member val State = CellState.RBC with get, set
 
     interface KdTree.I2DCoords with
         member this.X = this.Cx
         member this.Y = this.Cy
 
-
-let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (img: Image<Gray, float32>) (config: Config.Config) : Cell list =
-    if ellipses.IsEmpty
-    then
+let findCells (ellipses : Ellipse list) (parasites : ParasitesMarker.Result) (width : int) (height : int) (config : Config.Config) : Cell list =
+    if ellipses.IsEmpty then
         []
     else
-        let infection = parasites.infection.Copy() // To avoid to modify the parameter.
-
         // This is the minimum window size to check if other ellipses touch 'e'.
-        let searchRegion (e: Ellipse) = { KdTree.minX = e.Cx - (e.A + config.RBCRadius.Max)
-                                          KdTree.maxX = e.Cx + (e.A + config.RBCRadius.Max)
-                                          KdTree.minY = e.Cy - (e.A + config.RBCRadius.Max)
-                                          KdTree.maxY = e.Cy + (e.A + config.RBCRadius.Max) }
+        let searchRegion (e : Ellipse) =
+            {
+                KdTree.minX = e.Cx - (e.A + config.RBCRadius.Max)
+                KdTree.maxX = e.Cx + (e.A + config.RBCRadius.Max)
+                KdTree.minY = e.Cy - (e.A + config.RBCRadius.Max)
+                KdTree.maxY = e.Cy + (e.A + config.RBCRadius.Max)
+            }
 
         // The minimum window to contain a given ellipse.
-        let ellipseWindow (e: Ellipse) =
+        let ellipseWindow (e : Ellipse) =
             let cx, cy = roundInt e.Cx, roundInt e.Cy
             let a = int (e.A + 0.5f)
             cx - a, cy - a, cx + a, cy + a
 
-        let w = img.Width
-        let w_f = float32 w
-        let h = img.Height
-        let h_f = float32 h
-
         // Return 'true' if the point 'p' is owned by e.
         // The lines represents all intersections with other ellipses.
-        let pixelOwnedByE (p: PointF) (e: Ellipse) (others: (Ellipse * Line) list) =
+        let pixelOwnedByE (p : PointF) (e : EllipseFlaggedKd) (neighbors : (EllipseFlaggedKd * PointF * PointF) list) =
             e.Contains p.X p.Y &&
             seq {
-                let c = PointF(e.Cx, e.Cy)
-
-                for e', d1 in others do
-                    let d2 = lineFromTwoPoints c p
-                    let c' = PointF(e'.Cx, e'.Cy)
-                    let v = pointFromTwoLines d1 (lineFromTwoPoints c c')
-                    let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c'
-                    if d2.Valid
-                    then
-                        let p' = Utils.pointFromTwoLines d1 d2
-                        let delta, delta' =
-                            let d = c.X - p.X
-                            // To avoid rounding.
-                            if abs d < 0.001f then c.Y - p.Y, c.Y - p'.Y else d, c.X - p'.X
-
-                        // Yield 'false' when the point is owned by another ellipse.
-                        if case1
-                        then
-                            yield sign delta <> sign delta' || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p
+                let c = PointF (e.Cx, e.Cy)
+
+                for e', d1 in
+                    (neighbors
+                    |> List.choose (
+                        fun (otherE, p1, p2) ->
+                            if otherE.State = CellState.Removed then
+                                None
+                            else
+                                Some (otherE, Utils.lineFromTwoPoints p1 p2)
+                    )) do
+                    if e'.State = e.State then // Peculiar vs peculiar or RBC vs RBC.
+                        let d2 = lineFromTwoPoints c p
+                        let c' = PointF (e'.Cx, e'.Cy)
+                        let v = pointFromTwoLines d1 (lineFromTwoPoints c c')
+                        let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c'
+                        if not (Single.IsInfinity d2.A) then
+                            let p' = Utils.pointFromTwoLines d1 d2
+                            let delta, delta' =
+                                let dx1, dx2 = (c.X - p.X), (c.X - p'.X)
+                                // To avoid rounding issue.
+                                if abs dx1 < 0.01f || abs dx2 < 0.01f then c.Y - p.Y, c.Y - p'.Y else dx1, dx2
+
+                            // Yield 'false' when the point is owned by another ellipse.
+                            if case1 then
+                                yield sign delta <> sign delta' || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p
+                            else
+                                yield sign delta = sign delta' && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p
                         else
-                            yield sign delta = sign delta' && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p
+                            yield case1
+
+                    elif e.State = CellState.Peculiar then // A peculiar always win against a RBC.
+                        yield true
                     else
-                        yield case1
+                        yield not <| e'.Contains p.X p.Y
+
             } |> Seq.forall id
 
         let ellipses = ellipses |> List.map EllipseFlaggedKd
 
         // 1) Associate touching ellipses with each ellipses and remove ellipse with more than two intersections.
         let tree = KdTree.Tree.BuildTree ellipses
-        let neighbors (e: EllipseFlaggedKd) : (EllipseFlaggedKd * PointF * PointF) list =
-            if not e.Removed
-            then
+        let neighbors (e : EllipseFlaggedKd) : (EllipseFlaggedKd * PointF * PointF) list =
+            if e.State <> CellState.Removed then
                 tree.Search (searchRegion e)
                     // We only keep the ellipses touching 'e'.
-                    |> List.choose (fun otherE ->
-                        if e <> otherE
-                        then
-                            match EEOver.EEOverlapArea e otherE with
-                            | Some (_, px, _) when px.Length > 2 ->
-                                otherE.Removed <- true
-                                None
-                            | Some (area, px, py) when area > 0.f && px.Length = 2 ->
-                                Some (otherE, PointF(px.[0], py.[0]), PointF(px.[1], py.[1]))
-                            | _ ->
+                    |> List.choose (
+                        fun otherE ->
+                            if e <> otherE then
+                                match EEOver.EEOverlapArea e otherE with
+                                | Some (_, px, _) when px.Length > 2 ->
+                                    otherE.State <- CellState.Removed
+                                    None
+                                | Some (area, px, py) when area > 0.f && px.Length = 2 ->
+                                    Some (otherE, PointF (px.[0], py.[0]), PointF (px.[1], py.[1]))
+                                | _ ->
+                                    None
+                            else
                                 None
-                        else
-                            None )
+                    )
             else
                 []
 
-        // We reverse the list to get the lower score ellipses first.
-        let ellipsesWithNeigbors = ellipses |> List.map (fun e -> e, neighbors e) |> List.rev
+        let ellipsesWithNeigbors = ellipses |> List.map (fun e -> e, neighbors e)
 
         // 2) Remove ellipses touching the edges.
+        let widthF, heightF = float32 width, float32 height
         for e in ellipses do
-            if e.isOutside w_f h_f then e.Removed <- true
+            if e.IsOutside widthF heightF then e.State <- CellState.Removed
 
         // 3) Remove ellipses with a high standard deviation (high contrast).
-        let imgData = img.Data
-        let globalStdDeviation = MathNet.Numerics.Statistics.Statistics.PopulationStandardDeviation(seq {
+        // Obsolete. It was useful when the ellipses result quality wasn't good.
+        (* let imgData = img.Data
+        let globalStdDeviation = MathNet.Numerics.Statistics.Statistics.PopulationStandardDeviation (seq {
             for y in 0 .. h - 1 do
                 for x in 0 .. w - 1 do
                     yield float imgData.[y, x, 0] })
 
         for e in ellipses do
-            if not e.Removed
-            then
+            if not e.Removed then
                 let shrinkedE = e.Scale 0.9f
                 let minX, minY, maxX, maxY = ellipseWindow shrinkedE
 
                 let stdDeviation = MathNet.Numerics.Statistics.Statistics.StandardDeviation (seq {
                     for y in (if minY < 0 then 0 else minY) .. (if maxY >= h then h - 1 else maxY) do
                         for x in (if minX < 0 then 0 else minX) .. (if maxX >= w then w - 1 else maxX) do
-                            if shrinkedE.Contains (float32 x) (float32 y)
-                            then
+                            if shrinkedE.Contains (float32 x) (float32 y) then
                                 yield float imgData.[y, x, 0] })
 
                 if stdDeviation > globalStdDeviation * config.Parameters.standardDeviationMaxRatio then
-                    e.Removed <- true
-
+                    e.Removed <- true *)
 
         // 4) Remove ellipses with little area.
         let minArea = config.RBCRadius.MinArea
         for e, neighbors in ellipsesWithNeigbors do
-            if not e.Removed
-            then
+            if e.State <> CellState.Removed then
                 let minX, minY, maxX, maxY = ellipseWindow e
 
                 let mutable area = 0
-                for y in (if minY < 0 then 0 else minY) .. (if maxY >= h then h - 1 else maxY) do
-                    for x in (if minX < 0 then 0 else minX) .. (if maxX >= w then w - 1 else maxX) do
-                        let p = PointF(float32 x, float32 y)
-                        if pixelOwnedByE p e (neighbors |> List.choose (fun (otherE, p1, p2) -> if otherE.Removed then None else Some (otherE :> Ellipse, Utils.lineFromTwoPoints p1 p2)))
-                        then
+                for y = (if minY < 0 then 0 else minY) to (if maxY >= height then height - 1 else maxY) do
+                    for x = (if minX < 0 then 0 else minX) to (if maxX >= width then width - 1 else maxX) do
+                        let p = PointF (float32 x, float32 y)
+                        if pixelOwnedByE p e neighbors then
                             area <- area + 1
 
-                if area < int minArea
-                then
-                    e.Removed <- true
+                if area < int minArea then
+                    e.State <- CellState.Removed
+
+        // 5) Define non-rbc (peculiar) cells.
+        let darkStainData = parasites.darkStain.Data
+        ellipsesWithNeigbors
+        |> List.choose (
+            fun (e, neighbors) ->
+                if e.State = CellState.Removed then
+                    None
+                else
+                    let mutable darkStainPixels = 0
+                    let mutable nbElement = 0
+                    let minX, minY, maxX, maxY = ellipseWindow e
+                    for y = minY to maxY do
+                        for x = minX to maxX do
+                            let p = PointF (float32 x, float32 y)
+                            if pixelOwnedByE p e neighbors then
+                                nbElement <- nbElement + 1
+                                if darkStainData.[y, x, 0] > 0uy then
+                                    darkStainPixels <- darkStainPixels + 1
+
+                    if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement) then Some e else None
+        )
+
+        // We do not change the state during the process to avoid to have peculiar neighbors which change the behavior of 'pixelOwnedByE'.
+        |> List.iter (fun e -> e.State <- CellState.Peculiar)
 
         // 5) Define pixels associated to each ellipse and create the cells.
+        let diameterParasiteSquared = (2.f * config.RBCRadius.ParasiteRadius) ** 2.f |> roundInt
+        let minimumParasiteArea = config.RBCRadius.MinimumParasiteArea |> roundInt
+
+        let nucleusData = parasites.nucleus.Copy().Data // Will be modified thus the copy.
+        let parasiteData = parasites.parasite.Data
+        let darkStainData = parasites.darkStain.Data
+
         ellipsesWithNeigbors
-        |> List.choose (fun (e, neighbors) ->
-            if e.Removed
-            then
-                None
-            else
-                let minX, minY, maxX, maxY = ellipseWindow e
+        |> List.choose (
+            fun (e, neighbors) ->
+                if e.State = CellState.Removed then
+                    None
+                else
+                    let minX, minY, maxX, maxY = ellipseWindow e
+
+                    let nucleusPixels = List<Point> ()
+                    let parasitePixels = List<Point> ()
+
+                    let mutable nbElement = 0
+
+                    let elements = new Matrix<byte> (maxY - minY + 1, maxX - minX + 1)
+                    for y = minY to maxY do
+                        for x = minX to maxX do
+                            let p = PointF (float32 x, float32 y)
+                            if pixelOwnedByE p e neighbors then
+                                elements.[y - minY, x - minX] <- 1uy
+                                nbElement <- nbElement + 1
+
+                                if nucleusData.[y, x, 0] > 0uy then
+                                    nucleusPixels.Add (Point (x, y))
+
+                                if parasiteData.[y, x, 0] > 0uy then
+                                    parasitePixels.Add (Point (x, y))
+
+                    let parasiteArea =
+                        if nucleusPixels.Count > 0 then
+                            seq {
+                                for parasitePixel in parasitePixels do
+                                    if nucleusPixels.Exists (fun p -> pown (p.X - parasitePixel.X) 2 + pown (p.Y - parasitePixel.Y) 2 <= diameterParasiteSquared) then
+                                        yield 1
+                            } |> Seq.sum
+                        else
+                            0
 
-                let infectedPixels = List<Point>()
-                let mutable stainPixels = 0
-                let mutable darkStainPixels = 0
-                let mutable nbElement = 0
-
-                let elements = new Matrix<byte>(maxY - minY + 1, maxX - minX + 1)
-                for y in minY .. maxY do
-                    for x in minX .. maxX do
-                        let p = PointF(float32 x, float32 y)
-                        if pixelOwnedByE p e (neighbors |> List.choose (fun (otherE, p1, p2) -> if otherE.Removed then None else Some (otherE :> Ellipse, Utils.lineFromTwoPoints p1 p2)))
-                        then
-                            elements.[y-minY, x-minX] <- 1uy
-                            nbElement <- nbElement + 1
-
-                            if infection.Data.[y, x, 0] > 0uy
-                            then
-                                infectedPixels.Add(Point(x, y))
-
-                            if parasites.stain.Data.[y, x, 0] > 0uy
-                            then
-                                stainPixels <- stainPixels + 1
-
-                            if parasites.darkStain.Data.[y, x, 0] > 0uy
-                            then
-                                darkStainPixels <- darkStainPixels + 1
-
-                let cellClass =
-                    if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement) ||
-                       float stainPixels > config.Parameters.maxStainRatio * (float nbElement)
-                    then
-                        Peculiar
-                    elif infectedPixels.Count >= 1
-                    then
-                        let infectionToRemove = ImgTools.connectedComponents parasites.stain infectedPixels
-                        for p in infectionToRemove do
-                            infection.Data.[p.Y, p.X, 0] <- 0uy
-                        InfectedRBC
-                    else
-                        HealthyRBC
+                    let cellClass =
+                        if e.State = CellState.Peculiar then
+                            Peculiar
 
-                Some { cellClass = cellClass
-                       center = Point(roundInt e.Cx, roundInt e.Cy)
-                       infectedArea = infectedPixels.Count
-                       stainArea = stainPixels
-                       elements = elements })
+                        elif nucleusPixels.Count > 0 && parasiteArea >= minimumParasiteArea then
+                            let infectionToRemove = Morpho.connectedComponents parasites.parasite nucleusPixels
+                            for p in infectionToRemove do
+                                nucleusData.[p.Y, p.X, 0] <- 0uy
+                            InfectedRBC
+
+                        else
+                            HealthyRBC
+
+                    Some
+                        {
+                            cellClass = cellClass
+                            center = Point (roundInt e.Cx, roundInt e.Cy)
+                            nucleusArea = if cellClass = InfectedRBC then nucleusPixels.Count else 0
+                            parasiteArea = parasiteArea
+                            elements = elements
+                        }
+        )