Use two radius in the configuration, one computed with the image resolution and one...
[master-thesis.git] / Parasitemia / Parasitemia / MainAnalysis.fs
index ec2aabb..8f59514 100644 (file)
@@ -1,8 +1,11 @@
 module ImageAnalysis
 
 open System
+open System.Linq
 open System.Drawing
 
+open FSharp.Collections.ParallelSeq
+
 open Emgu.CV
 open Emgu.CV.Structure
 
@@ -11,34 +14,65 @@ open ImgTools
 open Config
 open Types
 
+let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportProgress: (int -> unit) option) : Cell list =
+    // To report the progress of this function from 0 to 100.
+    let inline report (percent: int) =
+        match reportProgress with
+        | Some f -> f percent
+        | _ -> ()
+
+    let inline buildLogWithName (text: string) = sprintf "(%s) %s" name text
+    let logWithName = buildLogWithName >> log
+    let inline logTimeWithName (text: string) (f: unit -> 'a) : 'a = logTime (buildLogWithName text) f
 
-let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) : Cell list =
-    let scaledImg = if config.Parameters.scale = 1.0 then img else img.Resize(config.Parameters.scale, CvEnum.Inter.Area)
+    logWithName "Starting analysis ..."
 
-    use green = scaledImg.Item(1)
+    use green = img.Item(1)
     let greenFloat = green.Convert<Gray, float32>()
-    let filteredGreen = gaussianFilter greenFloat (float config.Parameters.preFilterSigma)
+    let filteredGreen = gaussianFilter greenFloat config.LPFStandardDeviation
+
+    logWithName (sprintf "Nominal erytrocyte diameter: %A" config.RBCRadiusByResolution)
+
+    let initialAreaOpening = int <| config.RBCRadiusByResolution.Area * config.Parameters.ratioAreaPaleCenter * 1.2f // We do an area opening a little larger to avoid to do a second one in the case the radius found is near the initial one.
+    logTimeWithName "Area opening number one" (fun () -> ImgTools.areaOpenF filteredGreen initialAreaOpening)
 
-    logTime "areaOpen 1" (fun () -> ImgTools.areaOpenF filteredGreen config.Parameters.initialAreaOpen)
+    report 8
 
-    config.RBCRadius <- logTime "Granulometry" (fun() -> Granulometry.findRadius (filteredGreen.Convert<Gray, byte>()) (10, 100) 0.3 |> float32)
+    let range =
+        let delta = config.Parameters.granulometryRange * config.RBCRadiusByResolution.Pixel
+        int <| config.RBCRadiusByResolution.Pixel - delta, int <| config.RBCRadiusByResolution.Pixel + delta
+    //let r1 = log "Granulometry (morpho)" (fun() -> Granulometry.findRadiusByClosing (filteredGreen.Convert<Gray, byte>()) range 1.0 |> float32)
+    config.SetRBCRadius <| logTimeWithName "Granulometry (area)" (fun() -> Granulometry.findRadiusByAreaClosing filteredGreen range |> float32)
+    // log (sprintf "r1: %A, r2: %A" r1 r2)
 
-    let secondAreaOpen = int <| config.RBCArea / 3.f
-    if secondAreaOpen > config.Parameters.initialAreaOpen
+    logWithName (sprintf "Found erytrocyte diameter: %A" config.RBCRadius)
+
+    report 24
+
+    let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
+    if secondAreaOpening > initialAreaOpening
     then
-        logTime "areaOpen 2" (fun () -> ImgTools.areaOpenF filteredGreen secondAreaOpen)
+        logTimeWithName "Area opening number two" (fun () -> ImgTools.areaOpenF filteredGreen secondAreaOpening)
 
     let parasites, filteredGreenWhitoutStain = ParasitesMarker.find filteredGreen config
     //let parasites, filteredGreenWhitoutInfection, filteredGreenWhitoutStain = ParasitesMarker.findMa greenFloat filteredGreenFloat config
 
-    let edges, xGradient, yGradient = logTime "Finding edges" (fun () -> ImgTools.findEdges filteredGreenWhitoutStain)
-    logTime "Removing small connected components from thinning" (fun () -> removeArea edges (config.RBCRadius ** 2.f / 50.f |> int))
+    let edges, xGradient, yGradient = logTimeWithName "Finding edges" (fun () ->
+        let edges, xGradient, yGradient = ImgTools.findEdges filteredGreenWhitoutStain
+        removeArea edges (config.RBCRadius.Pixel ** 2.f / 50.f |> int)
+        edges, xGradient, yGradient)
 
-    let allEllipses, ellipses = logTime "Finding ellipses" (fun () ->
+    let allEllipses, ellipses = logTimeWithName "Finding ellipses" (fun () ->
         let matchingEllipses = Ellipse.find edges xGradient yGradient config
         matchingEllipses.Ellipses, matchingEllipses.PrunedEllipses)
 
-    let cells = logTime "Classifier" (fun () -> Classifier.findCells ellipses parasites filteredGreenWhitoutStain config)
+    report 80
+
+    let cells = logTimeWithName "Classifier" (fun () -> Classifier.findCells ellipses parasites filteredGreenWhitoutStain config)
+
+    report 100
+
+    logWithName "Analysis finished"
 
     // Output pictures if debug flag is set.
     match config.Debug with
@@ -58,7 +92,7 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) : Cell li
         drawEllipses imgAllEllipses allEllipses (Bgr(0.0, 240.0, 240.0)) 0.05
         saveImg imgAllEllipses (buildFileName " - ellipses - all.png")
 
-        let imgEllipses = img.Copy()
+        let imgEllipses = filteredGreenWhitoutStain.Convert<Bgr, byte>()
         drawEllipses imgEllipses ellipses (Bgr(0.0, 240.0, 240.0)) 1.0
         saveImg imgEllipses (buildFileName " - ellipses.png")
 
@@ -70,7 +104,7 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) : Cell li
         drawCells imgCells' true cells
         saveImg imgCells' (buildFileName " - cells - full.png")
 
-        let filteredGreenMaxima = gaussianFilter greenFloat config.Parameters.preFilterSigma
+        let filteredGreenMaxima = gaussianFilter greenFloat config.LPFStandardDeviation
         for m in ImgTools.findMaxima filteredGreenMaxima do
             ImgTools.drawPoints filteredGreenMaxima m 255.f
         saveImg filteredGreenMaxima (buildFileName " - filtered - maxima.png")
@@ -81,11 +115,33 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) : Cell li
 
         saveImg green (buildFileName " - green.png")
 
-        use blue  = scaledImg.Item(0)
+        use blue = img.Item(0)
         saveImg blue (buildFileName " - blue.png")
 
-        use red = scaledImg.Item(2)
+        use red = img.Item(2)
         saveImg red (buildFileName " - red.png")
     | _ -> ()
 
     cells
+
+// ID * cell list.
+let doMultipleAnalysis (imgs: (string * Config * Image<Bgr, byte>) list) (reportProgress: (int -> unit) option) : (string * Cell list) list =
+    let inline report (percent: int) =
+        match reportProgress with
+        | Some f -> f percent
+        | _ -> ()
+
+    let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int>()
+    let nbImgs = List.length imgs
+
+    let reportProgressImg (id: string) (progress: int) =
+        progressPerAnalysis.AddOrUpdate(id, progress, (fun _ _ -> progress)) |> ignore
+        report (progressPerAnalysis.Values.Sum() / nbImgs)
+
+    let nbConcurrentTaskLimit = 4 // To reduce the memory taken.
+    let n = Environment.ProcessorCount
+
+    imgs
+    |> PSeq.map (fun (id, config, img) -> id, doAnalysis img id config (Some (fun p -> reportProgressImg id p)))
+    |> PSeq.withDegreeOfParallelism (if n > nbConcurrentTaskLimit then nbConcurrentTaskLimit else n)
+    |> PSeq.toList