e83977ab6fde91e83aafb695b002871cd394546d
1
module ParasitemiaCore.Analysis
7 open FSharp.Collections.ParallelSeq
10 open Emgu.CV.Structure
21 /// Analyze the given image and detect reb blood cell (RBC) in it.
23 /// <param name="img">The image</param>
24 /// <param name="name">The name, used during logging</param>
25 /// <param name="config">The configuration, must not be shared with another analysis</param>
26 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
27 /// The first call returning 'false' will cancel the analysis.
28 /// The 'int' parameter correspond to the progression from 0 to 100</param>
29 /// <returns>A list of detected cells or nothing if the process has been cancelled</returns>
30 let doAnalysis (img
: Image<Bgr, byte
>) (name: string) (config
: Config) (reportProgress
: (int -> bool) option) : Cell list option =
32 // To report the progress of this function from 0 to 100.
33 // Return 'None' if the process must be aborted.
34 let reportWithVal (percent
: int) (value
: 'a) : 'a
option =
35 match reportProgress
with
42 let report (percent
: int) : unit option =
43 reportWithVal percent ()
45 let inline buildLogWithName
(text
: string) = sprintf
"№ %s: %s" name text
46 let logWithName mess
= Log.User(buildLogWithName
mess)
47 let inline logTimeWithName
(text: string) (f
: unit -> 'a option) : 'a
option = Log.LogWithTime((buildLogWithName
text), Severity.USER, f
)
49 // Monadic construction to be able to abort the progress when running.
53 logWithName "Starting analysis ..."
55 use img_float = img
.Convert<Bgr, float32
>()
57 use img_RBC = img_float.[1] // Green.
58 use img_RBC_filtered = gaussianFilter
img_RBC config
.LPFStandardDeviationRBC
60 use img_parasites = img_float.[2] // Red.
61 use img_parasites_filtered = gaussianFilter
img_parasites config.LPFStandardDeviationParasite
63 logWithName (sprintf
"Nominal erythrocyte diameter: %A" config.RBCRadiusByResolution)
65 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.
66 do! logTimeWithName
"First area opening" (fun () -> areaOpenF
img_RBC_filtered initialAreaOpening; report 10)
69 let delta = config.Parameters.granulometryRange
* config.RBCRadiusByResolution.Pixel
70 int <| config.RBCRadiusByResolution.Pixel - delta, int <| config.RBCRadiusByResolution.Pixel + delta
72 let! radius = logTimeWithName
"Granulometry (area)" (fun() -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing
img_RBC_filtered range |> float32
))
73 //let! radius = logTimeWithName "Granulometry (morpho)" (fun() -> reportWithVal 10 (Granulometry.findRadiusByClosing img_RBC_filtered range 1. true |> float32))
74 config.SetRBCRadius <| radius
76 logWithName (sprintf
"Found erythrocyte diameter: %A" config.RBCRadius)
81 let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
82 if secondAreaOpening > initialAreaOpening
84 logTimeWithName
"Second area opening" (fun () -> areaOpenF
img_RBC_filtered secondAreaOpening; report 30)
88 // Remove pale centers from the parasites image.
89 areaOpenF
img_parasites_filtered (int <| config.RBCRadiusByResolution.Area * config.Parameters.ratioAreaPaleCenter
)
91 // Removing parasites.
92 areaCloseF
img_RBC_filtered (roundInt
<| Const.PI * config.RBCRadius.ParasiteRadius ** 2.f
)
94 let! parasites, imgWhitoutParasite
, imgWithoutNucleus
=
95 logTimeWithName
"Parasites segmentation" (fun () -> reportWithVal 40 (ParasitesMarker.find
img_parasites_filtered config))
97 let! edges
, xGradient
, yGradient
= logTimeWithName
"Finding edges" (fun () ->
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
))
102 let! matchingEllipses
= logTimeWithName
"Finding ellipses" (fun () -> reportWithVal 60 (Ellipse.find
edges xGradient yGradient
config))
104 let! prunedEllipses
= logTimeWithName
"Ellipses pruning" (fun () -> reportWithVal 80 (matchingEllipses
.PrunedEllipses))
106 let! cells
= logTimeWithName
"Classifier" (fun () -> reportWithVal 100 (Classifier.findCells
prunedEllipses parasites img_RBC_filtered config))
108 logWithName "Analysis finished"
111 // Output pictures if debug flag is set.
112 match config.Debug with
114 let dirPath = System.IO.Path.Combine(output
, name)
115 System.IO.Directory.CreateDirectory dirPath |> ignore
117 let buildFileName postfix
= System.IO.Path.Combine(dirPath, name + postfix
)
119 IO.saveMat
(edges * 255.0) (buildFileName " - edges.png")
121 IO.saveImg
parasites.darkStain
(buildFileName " - parasites - dark stain.png")
122 IO.saveImg
parasites.parasite
(buildFileName " - parasites - stain.png")
123 IO.saveImg
parasites.nucleus
(buildFileName " - parasites - infection.png")
125 let imgAllEllipses = img_RBC_filtered.Copy()
126 Drawing.drawEllipses
imgAllEllipses matchingEllipses
.Ellipses (Gray(200.0)) 0.04
127 IO.saveImg
imgAllEllipses (buildFileName " - ellipses - all.png")
129 let imgEllipses = img_RBC_filtered.Convert<Bgr, byte
>()
130 Drawing.drawEllipses
imgEllipses prunedEllipses (Bgr(0.0, 240.0, 240.0)) 1.0
131 IO.saveImg
imgEllipses (buildFileName " - ellipses.png")
133 let imgCells = img
.Copy()
134 Drawing.drawCells
imgCells false cells
135 IO.saveImg
imgCells (buildFileName " - cells.png")
137 let imgCells' = img.Copy()
138 Drawing.drawCells imgCells' true cells
139 IO.saveImg
imgCells' (buildFileName " - cells - full.png")
141 let filteredRBCMaxima = gaussianFilter img_RBC config.LPFStandardDeviationRBC
142 for m in findMaxima filteredRBCMaxima do
143 Drawing.drawPoints filteredRBCMaxima m 255.f
144 IO.saveImg filteredRBCMaxima (buildFileName " - filtered - maxima.png")
146 IO.saveImg imgWhitoutParasite (buildFileName " - filtered closed stain.png")
147 IO.saveImg imgWithoutNucleus (buildFileName " - filtered closed infection.png")
149 IO.saveImg img_RBC_filtered (buildFileName " - source - RBC.png")
150 IO.saveImg img_parasites_filtered (buildFileName " - source - parasites.png")
152 IO.saveImg (normalize img_float.[2] 255.) (buildFileName " - source - red.png")
153 IO.saveImg (normalize img_float.[1] 255.) (buildFileName " - source - green.png")
154 IO.saveImg (normalize img_float.[0] 255.) (buildFileName " - source - blue.png")
160 /// Do multiple analyses on the same time. The number of concurrent process depends if the number of the core.
162 /// <param name="imgs">The images: (name * configuration * image)</param>
163 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
164 /// The first call returning 'false' will cancel the analysis.
165 /// The 'int' parameter correspond to the progression from 0 to 100</param>
166 /// <returns>'None' if the process has been cancelled or the list of result as (name * cells), 'name' corresponds to the given name<returns>
167 let doMultipleAnalysis (imgs: (string * Config * Image<Bgr, byte>) list) (reportProgress: (int -> bool) option) : (string * Cell list) list option =
168 let report (percent: int) : bool =
169 match reportProgress with
170 | Some f -> f percent
173 let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int>()
174 let nbImgs = List.length imgs
176 let reportProgressImg (id: string) (progress: int) =
177 progressPerAnalysis.AddOrUpdate(id, progress, (fun _ _ -> progress)) |> ignore
178 report (progressPerAnalysis.Values.Sum() / nbImgs)
180 let n = Environment.ProcessorCount
185 fun (id, config, img) ->
187 match doAnalysis img id config (Some (fun p -> reportProgressImg id p)) with
188 | Some result -> Some (id, result)
192 Log.Error("Analysis {0} failed: {1}", id, ex)
194 |> PSeq.withDegreeOfParallelism n
197 // If one of the analyses has been aborted we return 'None'.
198 if List.length results <> List.length imgs