1
module ParasitemiaCore.Analysis
7 open FSharp.Collections.ParallelSeq
10 open Emgu.CV.Structure
20 let warningRatioDifferenceRBCDiameter = 1.2
23 /// Analyze the given image and detect reb blood cell (RBC) in it.
25 /// <param name="img">The image</param>
26 /// <param name="name">The name, used during logging</param>
27 /// <param name="config">The configuration, must not be shared with another analysis</param>
28 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
29 /// The first call returning 'false' will cancel the analysis.
30 /// The 'int' parameter correspond to the progression from 0 to 100</param>
31 /// <returns>A list of detected cells or nothing if the process has been cancelled</returns>
32 let doAnalysis (img
: Image<Bgr, byte
>) (name : string) (config
: Config) (reportProgress
: (int -> bool) option) : AnalysisResult option =
34 // To report the progress of this function from 0 to 100.
35 // Return 'None' if the process must be aborted.
36 let reportWithVal (percent
: int) (value
: 'a) : 'a
option =
37 match reportProgress
with
38 | Some f
-> if f percent
then Some value else None
41 let report (percent
: int) : unit option =
42 reportWithVal percent ()
44 let inline buildLogWithName
(text
: string) = sprintf
"№ %s: %s" name text
45 let logWithName mess
= Log.Info "%s" (buildLogWithName
mess)
46 let inline logTimeWithName
(text : string) (f
: unit -> 'a option) : 'a
option = Log.LogWithTime Severity.INFO f
"%s" (buildLogWithName
text)
48 // Monadic construction to be able to abort the progress when running.
52 logWithName "Starting analysis ..."
54 use img_float = img
.Convert<Bgr, float32
> ()
56 use img_RBC = img_float.[1] // Green.
57 use img_RBC_filtered = gaussianFilter
img_RBC config
.LPFStandardDeviationRBC
59 use img_parasites = img_float.[2] // Red.
60 use img_parasites_filtered = gaussianFilter
img_parasites config.LPFStandardDeviationParasite
62 logWithName (sprintf
"Nominal erythrocyte diameter: %O" config.RBCRadiusByResolution)
64 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.
65 do! logTimeWithName
"First area opening" (fun () -> areaOpenF
img_RBC_filtered initialAreaOpening; report 10)
68 let delta = config.Parameters.granulometryRange
* config.RBCRadiusByResolution.Pixel
69 int <| config.RBCRadiusByResolution.Pixel - delta, int <| config.RBCRadiusByResolution.Pixel + delta
71 let! radius = logTimeWithName
"Granulometry (area)" (fun () -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing
img_RBC_filtered range |> float32
))
72 //let! radius = logTimeWithName "Granulometry (morpho)" (fun () -> reportWithVal 10 (Granulometry.findRadiusByClosing img_RBC_filtered range 1. true |> float32))
73 config.SetRBCRadius <| radius
75 logWithName (sprintf
"Found erythrocyte diameter: %O" config.RBCRadius)
80 let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
81 if secondAreaOpening > initialAreaOpening then
82 logTimeWithName
"Second area opening" (fun () -> areaOpenF
img_RBC_filtered secondAreaOpening; report 30)
86 // Remove pale centers from the parasites image.
87 areaOpenF
img_parasites_filtered (int <| config.RBCRadiusByResolution.Area * config.Parameters.ratioAreaPaleCenter
)
89 // Removing parasites.
90 areaCloseF
img_RBC_filtered (roundInt
<| Const.PI * config.RBCRadius.ParasiteRadius ** 2.f
)
92 let! parasites, imgWhitoutParasite
, imgWithoutNucleus
=
93 logTimeWithName
"Parasites segmentation" (fun () -> reportWithVal 40 (ParasitesMarker.find
img_parasites_filtered config))
95 let! edges
, xGradient
, yGradient
=
96 logTimeWithName
"Finding edges" (
98 let edges, xGradient
, yGradient
= Edges.find
img_RBC_filtered
99 removeArea
edges (config.RBCRadius.Pixel ** 2.f
/ 50.f
|> int)
100 reportWithVal 50 (edges, xGradient
, yGradient
)
103 let! matchingEllipses
= logTimeWithName
"Finding ellipses" (fun () -> reportWithVal 60 (Ellipse.find
edges xGradient yGradient
config))
105 let! prunedEllipses
= logTimeWithName
"Ellipses pruning" (fun () -> reportWithVal 80 (matchingEllipses
.PrunedEllipses))
107 let! cells
= logTimeWithName
"Classifier" (fun () -> reportWithVal 100 (Classifier.findCells
prunedEllipses parasites img.Width img.Height config))
110 if config.RBCRadiusByResolution.μm
/ config.RBCRadius.μm
> warningRatioDifferenceRBCDiameter then
111 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)
112 elif
config.RBCRadius.μm
/ config.RBCRadiusByResolution.μm
> warningRatioDifferenceRBCDiameter then
113 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)
115 logWithName "Analysis finished"
118 // Output pictures if debug flag is set.
119 match config.Debug with
121 let dirPath = System.IO.Path.Combine (output
, name)
122 System.IO.Directory.CreateDirectory dirPath |> ignore
124 let buildFileName postfix
= System.IO.Path.Combine (dirPath, name + postfix
)
126 IO.saveMat
(edges * 255.0) (buildFileName " - edges.png")
128 IO.saveImg
parasites.darkStain
(buildFileName " - parasites - dark stain.png")
129 IO.saveImg
parasites.parasite
(buildFileName " - parasites - stain.png")
130 IO.saveImg
parasites.nucleus
(buildFileName " - parasites - infection.png")
132 let imgAllEllipses = img_RBC_filtered.Copy ()
133 Drawing.drawEllipses
imgAllEllipses matchingEllipses
.Ellipses (Gray 200.0) 0.04
134 IO.saveImg
imgAllEllipses (buildFileName " - ellipses - all.png")
136 let imgEllipses = img_RBC_filtered.Convert<Bgr, byte
> ()
137 Drawing.drawEllipses
imgEllipses prunedEllipses (Bgr (0.0, 240.0, 240.0)) 1.0
138 IO.saveImg
imgEllipses (buildFileName " - ellipses.png")
140 let imgCells = img.Copy ()
141 Drawing.drawCells
imgCells false cells
142 IO.saveImg
imgCells (buildFileName " - cells.png")
144 let imgCells' = img.Copy ()
145 Drawing.drawCells imgCells' true cells
146 IO.saveImg
imgCells' (buildFileName " - cells - full.png")
148 (* let filteredRBCMaxima = gaussianFilter img_RBC config.LPFStandardDeviationRBC
149 for m in findMaxima filteredRBCMaxima do
150 Drawing.drawPoints filteredRBCMaxima m 255.f
151 IO.saveImg filteredRBCMaxima (buildFileName " - filtered - maxima.png") *)
153 IO.saveImg imgWhitoutParasite (buildFileName " - filtered closed stain.png")
154 IO.saveImg imgWithoutNucleus (buildFileName " - filtered closed infection.png")
156 IO.saveImg img_RBC_filtered (buildFileName " - source - RBC.png")
157 IO.saveImg img_parasites_filtered (buildFileName " - source - parasites.png")
159 IO.saveImg img_float.[2] (buildFileName " - source - red.png")
160 IO.saveImg img_float.[1] (buildFileName " - source - green.png")
161 IO.saveImg img_float.[0] (buildFileName " - source - blue.png")
167 RBCSize_μm = config.RBCRadius.μm
168 RBCSize_px = config.RBCRadius.Pixel
175 /// Do multiple analyses on the same time. The number of concurrent process depends if the number of the core.
177 /// <param name="imgs">The images: (name * configuration * image)</param>
178 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
179 /// The first call returning 'false' will cancel the analysis.
180 /// The 'int' parameter correspond to the progression from 0 to 100</param>
181 /// <returns>'None' if the process has been cancelled or the list of result as (name * cells), 'name' corresponds to the given name<returns>
182 let doMultipleAnalysis (imgs : (string * Config * Image<Bgr, byte>) list) (reportProgress : (int -> bool) option) : (string * AnalysisResult) list option =
183 let report (percent : int) : bool =
184 match reportProgress with
185 | Some f -> f percent
188 let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int> ()
189 let nbImgs = List.length imgs
191 let reportProgressImg (id : string) (progress : int) =
192 progressPerAnalysis.AddOrUpdate (id, progress, (fun _ _ -> progress)) |> ignore
193 report (progressPerAnalysis.Values.Sum () / nbImgs)
195 let n = Environment.ProcessorCount
200 fun (id, config, img) ->
202 match doAnalysis img id config (Some (fun p -> reportProgressImg id p)) with
203 | Some result -> Some (id, result)
207 Log.Error "Analysis %s failed: %O" id ex
210 |> PSeq.withDegreeOfParallelism n
213 // If one of the analyses has been aborted we return 'None'.
214 if List.length results <> List.length imgs then