9c85c7b1169b1ec906c0bca4985862884a548510
1
module ParasitemiaCore.Analysis
7 open FSharp.Collections.ParallelSeq
10 open Emgu.CV.Structure
20 /// Analyze the given image and detect reb blood cell (RBC) in it.
22 /// <param name="img">The image</param>
23 /// <param name="name">The name, used during logging</param>
24 /// <param name="config">The configuration, must not be shared with another analysis</param>
25 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
26 /// The first call returning 'false' will cancel the analysis.
27 /// The 'int' parameter correspond to the progression from 0 to 100</param>
28 /// <returns>A list of detected cells or nothing if the process has been cancelled</returns>
29 let doAnalysis (img
: Image<Bgr, byte
>) (name: string) (config
: Config) (reportProgress
: (int -> bool) option) : Cell list option =
31 // To report the progress of this function from 0 to 100.
32 // Return 'None' if the process must be aborted.
33 let reportWithVal (percent
: int) (value
: 'a) : 'a
option =
34 match reportProgress
with
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.User(buildLogWithName
mess)
46 let inline logTimeWithName
(text: string) (f
: unit -> 'a option) : 'a
option = Log.LogWithTime((buildLogWithName
text), Severity.USER, f
)
51 logWithName "Starting analysis ..."
53 use img_float = img
.Convert<Bgr, float32
>()
55 use img_RBC = img_float.[1] // mergeChannelsWithProjection img_float config.Parameters.averageColor_RBC config.Parameters.averageColor_BG 255.
56 use img_RBC_filtered = gaussianFilter
img_RBC config.LPFStandardDeviationRBC
58 use img_parasites = img_float.[2] // mergeChannelsWithProjection img_float config.Parameters.averageColor_Parasite config.Parameters.averageColor_RBC 255.
59 use img_parasites_filtered = gaussianFilter
img_parasites config.LPFStandardDeviationParasite
61 logWithName (sprintf
"Nominal erytrocyte diameter: %A" config.RBCRadiusByResolution)
63 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.
64 do! logTimeWithName
"First area opening" (fun () -> areaOpenF
img_RBC_filtered initialAreaOpening; report 10)
67 let delta = config.Parameters.granulometryRange
* config.RBCRadiusByResolution.Pixel
68 int <| config.RBCRadiusByResolution.Pixel - delta, int <| config.RBCRadiusByResolution.Pixel + delta
69 let! radius = logTimeWithName
"Granulometry (area)" (fun() -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing
img_RBC_filtered range |> float32
))
70 config.SetRBCRadius <| radius
72 logWithName (sprintf
"Found erytrocyte diameter: %A" config.RBCRadius)
77 let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
78 if secondAreaOpening > initialAreaOpening
80 logTimeWithName
"Second area opening" (fun () -> areaOpenF
img_RBC_filtered secondAreaOpening; report 30)
84 // Removing parasites.
85 areaCloseF
img_RBC_filtered (roundInt
<| Const.PI * config.RBCRadius.ParasiteRadius ** 2.f
)
87 let! parasites
, imgWhitoutParasite
, imgWithoutNucleus
=
88 logTimeWithName
"Parasites segmentation" (fun () -> reportWithVal 40 (ParasitesMarker.find
img_parasites_filtered config))
90 let! edges
, xGradient
, yGradient
= logTimeWithName
"Finding edges" (fun () ->
91 let edges, xGradient
, yGradient
= findEdges
img_RBC_filtered
92 removeArea
edges (config.RBCRadius.Pixel ** 2.f
/ 50.f
|> int)
93 reportWithVal 50 (edges, xGradient
, yGradient
))
95 let! matchingEllipses
= logTimeWithName
"Finding ellipses" (fun () -> reportWithVal 60 (Ellipse.find
edges xGradient yGradient
config))
97 let! prunedEllipses
= logTimeWithName
"Ellipses pruning" (fun () -> reportWithVal 80 (matchingEllipses
.PrunedEllipses))
99 let! cells
= logTimeWithName
"Classifier" (fun () -> reportWithVal 100 (Classifier.findCells
prunedEllipses parasites
img_RBC_filtered config))
101 logWithName "Analysis finished"
104 // Output pictures if debug flag is set.
105 match config.Debug with
107 let dirPath = System.IO.Path.Combine(output
, name)
108 System.IO.Directory.CreateDirectory dirPath |> ignore
110 let buildFileName postfix
= System.IO.Path.Combine(dirPath, name + postfix
)
112 saveMat
(edges * 255.0) (buildFileName " - edges.png")
114 saveImg parasites
.darkStain
(buildFileName " - parasites - dark stain.png")
115 saveImg parasites
.parasite
(buildFileName " - parasites - stain.png")
116 saveImg parasites
.nucleus
(buildFileName " - parasites - infection.png")
118 let imgAllEllipses = img
.Copy()
119 drawEllipses
imgAllEllipses matchingEllipses
.Ellipses (Bgr(255.0, 255.0, 255.0)) 0.04
120 saveImg
imgAllEllipses (buildFileName " - ellipses - all.png")
122 let imgEllipses = img_RBC_filtered.Convert<Bgr, byte
>()
123 drawEllipses
imgEllipses prunedEllipses (Bgr(0.0, 240.0, 240.0)) 1.0
124 saveImg
imgEllipses (buildFileName " - ellipses.png")
126 let imgCells = img
.Copy()
127 drawCells
imgCells false cells
128 saveImg
imgCells (buildFileName " - cells.png")
130 let imgCells' = img.Copy()
131 drawCells imgCells' true cells
132 saveImg
imgCells' (buildFileName " - cells - full.png")
134 let filteredGreenMaxima = gaussianFilter img_RBC config.LPFStandardDeviationRBC
135 for m in findMaxima filteredGreenMaxima do
136 drawPoints filteredGreenMaxima m 255.f
137 saveImg filteredGreenMaxima (buildFileName " - filtered - maxima.png")
139 saveImg img_RBC_filtered (buildFileName " - filtered.png")
140 saveImg imgWhitoutParasite (buildFileName " - filtered closed stain.png")
141 saveImg imgWithoutNucleus (buildFileName " - filtered closed infection.png")
143 saveImg img_RBC (buildFileName " - source - RBC.png")
144 saveImg img_parasites (buildFileName " - source - parasites.png")
146 saveImg (normalize img_float.[2] 255.) (buildFileName " - source - red.png")
147 saveImg (normalize img_float.[1] 255.) (buildFileName " - source - green.png")
148 saveImg (normalize img_float.[0] 255.) (buildFileName " - source - blue.png")
154 /// Do multiple analyses on the same time. The number of concurrent process depends if the number of the core.
156 /// <param name="imgs">The images: (name * configuration * image)</param>
157 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
158 /// The first call returning 'false' will cancel the analysis.
159 /// The 'int' parameter correspond to the progression from 0 to 100</param>
160 /// <returns>'None' if the process has been cancelled or the list of result as (name * cells), 'name' corresponds to the given name<returns>
161 let doMultipleAnalysis (imgs: (string * Config * Image<Bgr, byte>) list) (reportProgress: (int -> bool) option) : (string * Cell list) list option =
162 let report (percent: int) : bool =
163 match reportProgress with
164 | Some f -> f percent
167 let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int>()
168 let nbImgs = List.length imgs
170 let reportProgressImg (id: string) (progress: int) =
171 progressPerAnalysis.AddOrUpdate(id, progress, (fun _ _ -> progress)) |> ignore
172 report (progressPerAnalysis.Values.Sum() / nbImgs)
174 let n = Environment.ProcessorCount
179 fun (id, config, img) ->
180 match doAnalysis img id config (Some (fun p -> reportProgressImg id p)) with
181 | Some result -> Some (id, result)
183 |> PSeq.withDegreeOfParallelism n
186 // If one of the analyses has been aborted we return 'None'.
187 if List.length results <> List.length imgs