Project the colors to have the best contrast for RBCs and parasites analyze.
[master-thesis.git] / Parasitemia / ParasitemiaCore / MainAnalysis.fs
index be72a2b..cae6427 100644 (file)
@@ -16,8 +16,20 @@ open ImgTools
 open Config
 open Types
 
+/// <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.
+    // Return 'None' if the process must be aborted.
     let reportWithVal (percent: int) (value: 'a) : 'a option =
         match reportProgress with
         | Some f ->
@@ -29,7 +41,7 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportPr
     let report (percent: int) : unit option =
         reportWithVal percent ()
 
-    let inline buildLogWithName (text:  string) = sprintf "(%s) %s" name text
+    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)
 
@@ -38,22 +50,25 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportPr
 
         logWithName "Starting analysis ..."
 
-        use green = img.Item(1)
-        let greenFloat = green.Convert<Gray, float32>()
-        let filteredGreen = gaussianFilter greenFloat config.LPFStandardDeviation
+        use img_float = img.Convert<Bgr, float32>()
 
-        logWithName (sprintf "Nominal erytrocyte diameter: %A" config.RBCRadiusByResolution)
+        // use img_RBC = mergeChannels img_float config.Parameters.colorContribution_BG_RBC
+        use img_RBC = mergeChannelsWithProjection img_float (94.7f, 80.7f, 99.3f) (113.3f, 135.3f, 150.3f) 255.
+        let img_RBC_filtered = gaussianFilter img_RBC config.LPFStandardDeviationRBC
 
-        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.
-        do! logTimeWithName "First area opening" (fun () -> ImgTools.areaOpenF filteredGreen initialAreaOpening; report 10)
+        //use img_parasites = mergeChannels img_float config.Parameters.colorContribution_RBC_parasite
+        use img_parasites = mergeChannelsWithProjection img_float (76.f, 58.f, 94.f) (94.7f, 80.7f, 99.3f) 255.
 
-        //do! report 10
+        logWithName (sprintf "Nominal erytrocyte diameter: %A" config.RBCRadiusByResolution)
+
+        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 () -> ImgTools.areaOpenF img_RBC_filtered initialAreaOpening; report 10)
 
         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)
-        let! radius = logTimeWithName "Granulometry (area)" (fun() -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing filteredGreen range |> float32))
+        let! radius = logTimeWithName "Granulometry (area)" (fun() -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing img_RBC_filtered range |> float32))
         config.SetRBCRadius <| radius
 
         logWithName (sprintf "Found erytrocyte diameter: %A" config.RBCRadius)
@@ -64,15 +79,18 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportPr
             let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
             if secondAreaOpening > initialAreaOpening
             then
-                logTimeWithName "Second area opening" (fun () -> ImgTools.areaOpenF filteredGreen secondAreaOpening; report 30)
+                logTimeWithName "Second area opening" (fun () -> ImgTools.areaOpenF img_RBC_filtered secondAreaOpening; report 30)
             else
                 report 30
 
-        let parasites, filteredGreenWhitoutStain = ParasitesMarker.find filteredGreen config
+        // Removing of parasites.
+        ImgTools.areaCloseF img_RBC_filtered (roundInt <| Const.PI * config.RBCRadius.ParasiteRadius ** 2.f)
+
+        let parasites, filteredGreenWhitoutStain, filteredGreenWithoutInfection = ParasitesMarker.find img_parasites config
         //let parasites, filteredGreenWhitoutInfection, filteredGreenWhitoutStain = ParasitesMarker.findMa greenFloat filteredGreenFloat config
 
         let! edges, xGradient, yGradient = logTimeWithName "Finding edges" (fun () ->
-            let edges, xGradient, yGradient = ImgTools.findEdges filteredGreenWhitoutStain
+            let edges, xGradient, yGradient = ImgTools.findEdges img_RBC_filtered
             removeArea edges (config.RBCRadius.Pixel ** 2.f / 50.f |> int)
             reportWithVal 40 (edges, xGradient, yGradient))
 
@@ -80,7 +98,7 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportPr
 
         let! prunedEllipses = logTimeWithName "Ellipses pruning" (fun () -> reportWithVal 80 (matchingEllipses.PrunedEllipses))
 
-        let! cells = logTimeWithName "Classifier" (fun () -> reportWithVal 100 (Classifier.findCells prunedEllipses parasites filteredGreenWhitoutStain config))
+        let! cells = logTimeWithName "Classifier" (fun () -> reportWithVal 100 (Classifier.findCells prunedEllipses parasites img_RBC_filtered config))
 
         logWithName "Analysis finished"
 
@@ -103,7 +121,7 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportPr
                 drawEllipses imgAllEllipses matchingEllipses.Ellipses (Bgr(255.0, 255.0, 255.0)) 0.04
                 saveImg imgAllEllipses (buildFileName " - ellipses - all.png")
 
-                let imgEllipses = filteredGreenWhitoutStain.Convert<Bgr, byte>()
+                let imgEllipses = img_RBC_filtered.Convert<Bgr, byte>()
                 drawEllipses imgEllipses prunedEllipses (Bgr(0.0, 240.0, 240.0)) 1.0
                 saveImg imgEllipses (buildFileName " - ellipses.png")
 
@@ -115,22 +133,17 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportPr
                 drawCells imgCells' true cells
                 saveImg imgCells' (buildFileName " - cells - full.png")
 
-                let filteredGreenMaxima = gaussianFilter greenFloat config.LPFStandardDeviation
+                let filteredGreenMaxima = gaussianFilter img_RBC config.LPFStandardDeviationRBC
                 for m in ImgTools.findMaxima filteredGreenMaxima do
                     ImgTools.drawPoints filteredGreenMaxima m 255.f
                 saveImg filteredGreenMaxima (buildFileName " - filtered - maxima.png")
 
-                saveImg filteredGreen (buildFileName " - filtered.png")
+                saveImg img_RBC_filtered (buildFileName " - filtered.png")
                 saveImg filteredGreenWhitoutStain (buildFileName " - filtered closed stain.png")
-                //saveImg filteredGreenWhitoutInfection (buildFileName " - filtered closed infection.png")
-
-                saveImg green (buildFileName " - green.png")
-
-                use blue = img.Item(0)
-                saveImg blue (buildFileName " - blue.png")
+                saveImg filteredGreenWithoutInfection (buildFileName " - filtered closed infection.png")
 
-                use red = img.Item(2)
-                saveImg red (buildFileName " - red.png")
+                saveImg img_RBC (buildFileName " - source - RBC.png")
+                saveImg img_parasites (buildFileName " - source - parasites.png")
             | _ -> ()
 
         return cells }
@@ -138,8 +151,11 @@ let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportPr
 /// <summary>
 /// Do multiple analyses on the same time. The number of concurrent process depends if the number of the core.
 /// </summary>
-/// <param name="imgs"></param>
-/// <param name="reportProgress">An optional function to report progress. The process is aborted if the returned value is false</param>
+/// <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