* Modify a bit the parasite nucleus detection sensibility.
[master-thesis.git] / Parasitemia / ParasitemiaCore / MainAnalysis.fs
index 0faf54a..926aeac 100644 (file)
@@ -12,127 +12,158 @@ open Emgu.CV.Structure
 open Logger
 
 open Utils
+open Morpho
 open ImgTools
 open Config
 open Types
 
-let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportProgress: (int -> unit) option) : Cell list =
+/// <summary>
+/// Analyze the given image and detect reb blood cell (RBC) in it.
+/// </summary>
+/// <param name="img">The image</param>
+/// <param name="name">The name, used during logging</param>
+/// <param name="config">The configuration, must not be shared with another analysis</param>
+/// <param name="reportProgress">An optional function to report progress and/or cancel the process.
+///     The first call returning 'false' will cancel the analysis.
+///     The 'int' parameter correspond to the progression from 0 to 100</param>
+/// <returns>A list of detected cells or nothing if the process has been cancelled</returns>
+let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportProgress: (int -> bool) option) : Cell list option =
+
     // To report the progress of this function from 0 to 100.
-    let inline report (percent: int) =
+    // Return 'None' if the process must be aborted.
+    let reportWithVal (percent: int) (value: 'a) : 'a option =
         match reportProgress with
-        | Some f -> f percent
-        | _ -> ()
+        | Some f ->
+            if f percent
+            then Some value
+            else None
+        | _ -> Some value
 
-    let inline buildLogWithName (text:  string) = sprintf "(%s) %s" name text
-    let logWithName mess = Log.User(buildLogWithName mess)
-    let inline logTimeWithName (text: string) (f: unit -> 'a) : 'a = Log.LogWithTime((buildLogWithName text), Severity.USER, f)
+    let report (percent: int) : unit option =
+        reportWithVal percent ()
 
-    logWithName "Starting analysis ..."
+    let inline buildLogWithName (text: string) = sprintf "(%s) %s" name text
+    let logWithName mess = Log.User(buildLogWithName mess)
+    let inline logTimeWithName (text: string) (f: unit -> 'a option) : 'a option = Log.LogWithTime((buildLogWithName text), Severity.USER, f)
 
-    use green = img.Item(1)
-    let greenFloat = green.Convert<Gray, float32>()
-    let filteredGreen = gaussianFilter greenFloat config.LPFStandardDeviation
+    maybe {
+        do! report 0
 
-    logWithName (sprintf "Nominal erytrocyte diameter: %A" config.RBCRadiusByResolution)
+        logWithName "Starting analysis ..."
 
-    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)
+        use img_float = img.Convert<Bgr, float32>()
 
-    report 10
+        use img_RBC = img_float.[1] // mergeChannelsWithProjection img_float config.Parameters.averageColor_RBC config.Parameters.averageColor_BG 255.
+        use img_RBC_filtered = gaussianFilter img_RBC config.LPFStandardDeviationRBC
 
-    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)
+        use img_parasites = img_float.[2] // mergeChannelsWithProjection img_float config.Parameters.averageColor_Parasite config.Parameters.averageColor_RBC 255.
+        use img_parasites_filtered = gaussianFilter img_parasites config.LPFStandardDeviationParasite
 
-    logWithName (sprintf "Found erytrocyte diameter: %A" config.RBCRadius)
+        logWithName (sprintf "Nominal erythrocyte diameter: %A" config.RBCRadiusByResolution)
 
-    report 20
+        let initialAreaOpening = int <| config.RBCRadiusByResolution.Area * config.Parameters.ratioAreaPaleCenter * 1.1f // 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.
+        do! logTimeWithName "First area opening" (fun () -> areaOpenF img_RBC_filtered initialAreaOpening; report 10)
 
-    let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
-    if secondAreaOpening > initialAreaOpening
-    then
-        logTimeWithName "Area opening number two" (fun () -> ImgTools.areaOpenF filteredGreen secondAreaOpening)
+        let range =
+            let delta = config.Parameters.granulometryRange * config.RBCRadiusByResolution.Pixel
+            int <| config.RBCRadiusByResolution.Pixel - delta, int <| config.RBCRadiusByResolution.Pixel + delta
+        let! radius = logTimeWithName "Granulometry (area)" (fun() -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing img_RBC_filtered range |> float32))
+        config.SetRBCRadius <| radius
 
-    let parasites, filteredGreenWhitoutStain = ParasitesMarker.find filteredGreen config
-    //let parasites, filteredGreenWhitoutInfection, filteredGreenWhitoutStain = ParasitesMarker.findMa greenFloat filteredGreenFloat config
+        logWithName (sprintf "Found erythrocyte diameter: %A" config.RBCRadius)
 
-    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)
+        do! report 20
 
-    let matchingEllipses = logTimeWithName "Finding ellipses" (fun () -> Ellipse.find edges xGradient yGradient config)
+        do!
+            let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
+            if secondAreaOpening > initialAreaOpening
+            then
+                logTimeWithName "Second area opening" (fun () -> areaOpenF img_RBC_filtered secondAreaOpening; report 30)
+            else
+                report 30
 
-    report 60
+        // Removing parasites.
+        areaCloseF img_RBC_filtered (roundInt <| Const.PI * config.RBCRadius.ParasiteRadius ** 2.f)
 
-    let prunedEllipses = logTimeWithName "Ellipses pruning" (fun () -> matchingEllipses.PrunedEllipses)
+        let! parasites, imgWhitoutParasite, imgWithoutNucleus =
+            logTimeWithName "Parasites segmentation" (fun () -> reportWithVal 40 (ParasitesMarker.find img_parasites_filtered config))
 
-    report 80
+        let! edges, xGradient, yGradient = logTimeWithName "Finding edges" (fun () ->
+            let edges, xGradient, yGradient = Edges.find img_RBC_filtered
+            removeArea edges (config.RBCRadius.Pixel ** 2.f / 50.f |> int)
+            reportWithVal 50 (edges, xGradient, yGradient))
 
-    let cells = logTimeWithName "Classifier" (fun () -> Classifier.findCells prunedEllipses parasites filteredGreenWhitoutStain config)
+        let! matchingEllipses = logTimeWithName "Finding ellipses" (fun () -> reportWithVal 60 (Ellipse.find edges xGradient yGradient config))
 
-    report 100
+        let! prunedEllipses = logTimeWithName "Ellipses pruning" (fun () -> reportWithVal 80 (matchingEllipses.PrunedEllipses))
 
-    logWithName "Analysis finished"
+        let! cells = logTimeWithName "Classifier" (fun () -> reportWithVal 100 (Classifier.findCells prunedEllipses parasites img_RBC_filtered config))
 
-    // Output pictures if debug flag is set.
-    match config.Debug with
-    | DebugOn output ->
-        let dirPath = System.IO.Path.Combine(output, name)
-        System.IO.Directory.CreateDirectory dirPath |> ignore
+        logWithName "Analysis finished"
 
-        let buildFileName postfix = System.IO.Path.Combine(dirPath, name + postfix)
+        do
+            // Output pictures if debug flag is set.
+            match config.Debug with
+            | DebugOn output ->
+                let dirPath = System.IO.Path.Combine(output, name)
+                System.IO.Directory.CreateDirectory dirPath |> ignore
 
-        saveMat (edges * 255.0) (buildFileName " - edges.png")
+                let buildFileName postfix = System.IO.Path.Combine(dirPath, name + postfix)
 
-        saveImg parasites.darkStain (buildFileName " - parasites - dark stain.png")
-        saveImg parasites.stain (buildFileName " - parasites - stain.png")
-        saveImg parasites.infection (buildFileName " - parasites - infection.png")
+                IO.saveMat (edges * 255.0) (buildFileName " - edges.png")
 
-        let imgAllEllipses = img.Copy()
-        drawEllipses imgAllEllipses matchingEllipses.Ellipses (Bgr(255.0, 255.0, 255.0)) 0.04
-        saveImg imgAllEllipses (buildFileName " - ellipses - all.png")
+                IO.saveImg parasites.darkStain (buildFileName " - parasites - dark stain.png")
+                IO.saveImg parasites.parasite (buildFileName " - parasites - stain.png")
+                IO.saveImg parasites.nucleus (buildFileName " - parasites - infection.png")
 
-        let imgEllipses = filteredGreenWhitoutStain.Convert<Bgr, byte>()
-        drawEllipses imgEllipses prunedEllipses (Bgr(0.0, 240.0, 240.0)) 1.0
-        saveImg imgEllipses (buildFileName " - ellipses.png")
+                let imgAllEllipses = img.Copy()
+                Drawing.drawEllipses imgAllEllipses matchingEllipses.Ellipses (Bgr(255.0, 255.0, 255.0)) 0.04
+                IO.saveImg imgAllEllipses (buildFileName " - ellipses - all.png")
 
-        let imgCells = img.Copy()
-        drawCells imgCells false cells
-        saveImg imgCells (buildFileName " - cells.png")
+                let imgEllipses = img_RBC_filtered.Convert<Bgr, byte>()
+                Drawing.drawEllipses imgEllipses prunedEllipses (Bgr(0.0, 240.0, 240.0)) 1.0
+                IO.saveImg imgEllipses (buildFileName " - ellipses.png")
 
-        let imgCells' = img.Copy()
-        drawCells imgCells' true cells
-        saveImg imgCells' (buildFileName " - cells - full.png")
+                let imgCells = img.Copy()
+                Drawing.drawCells imgCells false cells
+                IO.saveImg imgCells (buildFileName " - cells.png")
 
-        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")
+                let imgCells' = img.Copy()
+                Drawing.drawCells imgCells' true cells
+                IO.saveImg imgCells' (buildFileName " - cells - full.png")
 
-        saveImg filteredGreen (buildFileName " - filtered.png")
-        saveImg filteredGreenWhitoutStain (buildFileName " - filtered closed stain.png")
-        //saveImg filteredGreenWhitoutInfection (buildFileName " - filtered closed infection.png")
+                let filteredGreenMaxima = gaussianFilter img_RBC config.LPFStandardDeviationRBC
+                for m in findMaxima filteredGreenMaxima do
+                    Drawing.drawPoints filteredGreenMaxima m 255.f
+                IO.saveImg filteredGreenMaxima (buildFileName " - filtered - maxima.png")
 
-        saveImg green (buildFileName " - green.png")
+                IO.saveImg img_RBC_filtered (buildFileName " - filtered.png")
+                IO.saveImg imgWhitoutParasite (buildFileName " - filtered closed stain.png")
+                IO.saveImg imgWithoutNucleus (buildFileName " - filtered closed infection.png")
 
-        use blue = img.Item(0)
-        saveImg blue (buildFileName " - blue.png")
+                IO.saveImg img_RBC (buildFileName " - source - RBC.png")
+                IO.saveImg img_parasites (buildFileName " - source - parasites.png")
 
-        use red = img.Item(2)
-        saveImg red (buildFileName " - red.png")
-    | _ -> ()
+                IO.saveImg (normalize img_float.[2] 255.) (buildFileName " - source - red.png")
+                IO.saveImg (normalize img_float.[1] 255.) (buildFileName " - source - green.png")
+                IO.saveImg (normalize img_float.[0] 255.) (buildFileName " - source - blue.png")
+            | _ -> ()
 
-    cells
+        return 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) =
+/// <summary>
+/// Do multiple analyses on the same time. The number of concurrent process depends if the number of the core.
+/// </summary>
+/// <param name="imgs">The images: (name * configuration * image)</param>
+/// <param name="reportProgress">An optional function to report progress and/or cancel the process.
+///     The first call returning 'false' will cancel the analysis.
+///     The 'int' parameter correspond to the progression from 0 to 100</param>
+/// <returns>'None' if the process has been cancelled or the list of result as (name * cells), 'name' corresponds to the given name<returns>
+let doMultipleAnalysis (imgs: (string * Config * Image<Bgr, byte>) list) (reportProgress: (int -> bool) option) : (string * Cell list) list option =
+    let report (percent: int) : bool =
         match reportProgress with
         | Some f -> f percent
-        | _ -> ()
+        | _ -> true
 
     let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int>()
     let nbImgs = List.length imgs
@@ -143,7 +174,18 @@ let doMultipleAnalysis (imgs: (string * Config * Image<Bgr, byte>) list) (report
 
     let n = Environment.ProcessorCount
 
-    imgs
-    |> PSeq.map (fun (id, config, img) -> id, doAnalysis img id config (Some (fun p -> reportProgressImg id p)))
-    |> PSeq.withDegreeOfParallelism n
-    |> PSeq.toList
+    let results =
+        imgs
+        |> PSeq.choose (
+            fun (id, config, img) ->
+                match doAnalysis img id config (Some (fun p -> reportProgressImg id p)) with
+                | Some result -> Some (id, result)
+                | None -> None)
+        |> PSeq.withDegreeOfParallelism n
+        |> PSeq.toList
+
+    // If one of the analyses has been aborted we return 'None'.
+    if List.length results <> List.length imgs
+    then None
+    else Some results
+