Add launch settings.
[master-thesis.git] / Parasitemia / ParasitemiaCore / Analysis.fs
index afcf4df..1ba273c 100644 (file)
@@ -2,7 +2,6 @@
 
 open System
 open System.Linq
-open System.Drawing
 
 open FSharp.Collections.ParallelSeq
 
@@ -17,6 +16,8 @@ open ImgTools
 open Config
 open Types
 
+let warningRatioDifferenceRBCDiameter = 1.2
+
 /// <summary>
 /// Analyze the given image and detect reb blood cell (RBC) in it.
 /// </summary>
@@ -27,7 +28,7 @@ open Types
 ///     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 =
+let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (reportProgress : (int -> bool) option) : AnalysisResult option =
 
     // To report the progress of this function from 0 to 100.
     // Return 'None' if the process must be aborted.
@@ -40,8 +41,8 @@ let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (repor
         reportWithVal percent ()
 
     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)
+    let logWithName mess = Log.Info "%s" (buildLogWithName mess)
+    let inline logTimeWithName (text : string) (f : unit -> 'a option) : 'a option = Log.LogWithTime Severity.INFO f "%s" (buildLogWithName text)
 
     // Monadic construction to be able to abort the progress when running.
     maybe {
@@ -49,7 +50,7 @@ let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (repor
 
         logWithName "Starting analysis ..."
 
-        use img_float = img.Convert<Bgr, float32>()
+        use img_float = img.Convert<Bgr, float32> ()
 
         use img_RBC = img_float.[1] // Green.
         use img_RBC_filtered = gaussianFilter img_RBC config.LPFStandardDeviationRBC
@@ -66,8 +67,8 @@ let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (repor
             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))
-        //let! radius = logTimeWithName "Granulometry (morpho)" (fun() -> reportWithVal 10 (Granulometry.findRadiusByClosing img_RBC_filtered range 1. true |> float32))
+        let! radius = logTimeWithName "Granulometry (area)" (fun () -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing img_RBC_filtered range |> float32))
+        //let! radius = logTimeWithName "Granulometry (morpho)" (fun () -> reportWithVal 10 (Granulometry.findRadiusByClosing img_RBC_filtered range 1. true |> float32))
         config.SetRBCRadius <| radius
 
         logWithName (sprintf "Found erythrocyte diameter: %O" config.RBCRadius)
@@ -90,10 +91,13 @@ let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (repor
         let! parasites, imgWhitoutParasite, imgWithoutNucleus =
             logTimeWithName "Parasites segmentation" (fun () -> reportWithVal 40 (ParasitesMarker.find img_parasites_filtered config))
 
-        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! 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! matchingEllipses = logTimeWithName "Finding ellipses" (fun () -> reportWithVal 60 (Ellipse.find edges xGradient yGradient config))
 
@@ -101,16 +105,22 @@ let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (repor
 
         let! cells = logTimeWithName "Classifier" (fun () -> reportWithVal 100 (Classifier.findCells prunedEllipses parasites img.Width img.Height config))
 
+        do
+            if config.RBCRadiusByResolution.μm / config.RBCRadius.μm > warningRatioDifferenceRBCDiameter then
+                logWithName (sprintf "Warning: erythrocyte diameter found is too low compared to the nominal erythrocyte diameter, maybe the PPI image resolution is lesser than %.0f ppi" config.Parameters.resolution)
+            elif config.RBCRadius.μm / config.RBCRadiusByResolution.μm > warningRatioDifferenceRBCDiameter then
+                logWithName (sprintf "Warning: erythrocyte diameter found is too high compared to the nominal erythrocyte diameter, maybe the PPI image resolution is higher than %.0f" config.Parameters.resolution)
+
         logWithName "Analysis finished"
 
         do
             // Output pictures if debug flag is set.
             match config.Debug with
             | DebugOn output ->
-                let dirPath = System.IO.Path.Combine(output, name)
+                let dirPath = System.IO.Path.Combine (output, name)
                 System.IO.Directory.CreateDirectory dirPath |> ignore
 
-                let buildFileName postfix = System.IO.Path.Combine(dirPath, name + postfix)
+                let buildFileName postfix = System.IO.Path.Combine (dirPath, name + postfix)
 
                 IO.saveMat (edges * 255.0) (buildFileName " - edges.png")
 
@@ -118,19 +128,19 @@ let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (repor
                 IO.saveImg parasites.parasite (buildFileName " - parasites - stain.png")
                 IO.saveImg parasites.nucleus (buildFileName " - parasites - infection.png")
 
-                let imgAllEllipses = img_RBC_filtered.Copy()
-                Drawing.drawEllipses imgAllEllipses matchingEllipses.Ellipses (Gray(200.0)) 0.04
+                let imgAllEllipses = img_RBC_filtered.Copy ()
+                Drawing.drawEllipses imgAllEllipses matchingEllipses.Ellipses (Gray 200.0) 0.04
                 IO.saveImg imgAllEllipses (buildFileName " - ellipses - all.png")
 
-                let imgEllipses = img_RBC_filtered.Convert<Bgr, byte>()
-                Drawing.drawEllipses imgEllipses prunedEllipses (Bgr(0.0, 240.0, 240.0)) 1.0
+                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()
+                let imgCells = img.Copy ()
                 Drawing.drawCells imgCells false cells
                 IO.saveImg imgCells (buildFileName " - cells.png")
 
-                let imgCells' = img.Copy()
+                let imgCells' = img.Copy ()
                 Drawing.drawCells imgCells' true cells
                 IO.saveImg imgCells' (buildFileName " - cells - full.png")
 
@@ -150,29 +160,36 @@ let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (repor
                 IO.saveImg img_float.[0] (buildFileName " - source - blue.png")
             | _ -> ()
 
-        return cells
+        return
+            {
+                Cells = cells
+                RBCSize_μm = config.RBCRadius.μm
+                RBCSize_px = config.RBCRadius.Pixel
+            }
+
+        //return cells
     }
 
 /// <summary>
-/// Do multiple analyses on the same time. The number of concurrent process depends if the number of the core.
+/// Do multiple analyses on the same time. The number of concurrent process depends on 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 =
+/// <return>'None' if the process has been cancelled or the list of result as (name * cells), 'name' corresponds to the given name</return>
+let doMultipleAnalysis (imgs : (string * Config * Image<Bgr, byte>) list) (reportProgress : (int -> bool) option) : (string * AnalysisResult) list option =
     let report (percent : int) : bool =
         match reportProgress with
         | Some f -> f percent
         | _ -> true
 
-    let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int>()
+    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)
+        progressPerAnalysis.AddOrUpdate (id, progress, (fun _ _ -> progress)) |> ignore
+        report (progressPerAnalysis.Values.Sum () / nbImgs)
 
     let n = Environment.ProcessorCount
 
@@ -186,7 +203,7 @@ let doMultipleAnalysis (imgs : (string * Config * Image<Bgr, byte>) list) (repor
                     | None -> None
                 with
                 | ex ->
-                    Log.Error("Analysis {0} failed: {1}", id, ex)
+                    Log.Error "Analysis %s failed: %O" id ex
                     None
         )
         |> PSeq.withDegreeOfParallelism n