Add launch settings.
[master-thesis.git] / Parasitemia / ParasitemiaCore / Analysis.fs
1 module ParasitemiaCore.Analysis
2
3 open System
4 open System.Linq
5
6 open FSharp.Collections.ParallelSeq
7
8 open Emgu.CV
9 open Emgu.CV.Structure
10
11 open Logger
12
13 open Utils
14 open Morpho
15 open ImgTools
16 open Config
17 open Types
18
19 let warningRatioDifferenceRBCDiameter = 1.2
20
21 /// <summary>
22 /// Analyze the given image and detect reb blood cell (RBC) in it.
23 /// </summary>
24 /// <param name="img">The image</param>
25 /// <param name="name">The name, used during logging</param>
26 /// <param name="config">The configuration, must not be shared with another analysis</param>
27 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
28 /// The first call returning 'false' will cancel the analysis.
29 /// The 'int' parameter correspond to the progression from 0 to 100</param>
30 /// <returns>A list of detected cells or nothing if the process has been cancelled</returns>
31 let doAnalysis (img : Image<Bgr, byte>) (name : string) (config : Config) (reportProgress : (int -> bool) option) : AnalysisResult option =
32
33 // To report the progress of this function from 0 to 100.
34 // Return 'None' if the process must be aborted.
35 let reportWithVal (percent : int) (value : 'a) : 'a option =
36 match reportProgress with
37 | Some f -> if f percent then Some value else None
38 | _ -> Some value
39
40 let report (percent : int) : unit option =
41 reportWithVal percent ()
42
43 let inline buildLogWithName (text : string) = sprintf "№ %s: %s" name text
44 let logWithName mess = Log.Info "%s" (buildLogWithName mess)
45 let inline logTimeWithName (text : string) (f : unit -> 'a option) : 'a option = Log.LogWithTime Severity.INFO f "%s" (buildLogWithName text)
46
47 // Monadic construction to be able to abort the progress when running.
48 maybe {
49 do! report 0
50
51 logWithName "Starting analysis ..."
52
53 use img_float = img.Convert<Bgr, float32> ()
54
55 use img_RBC = img_float.[1] // Green.
56 use img_RBC_filtered = gaussianFilter img_RBC config.LPFStandardDeviationRBC
57
58 use img_parasites = img_float.[2] // Red.
59 use img_parasites_filtered = gaussianFilter img_parasites config.LPFStandardDeviationParasite
60
61 logWithName (sprintf "Nominal erythrocyte diameter: %O" config.RBCRadiusByResolution)
62
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)
65
66 let range =
67 let delta = config.Parameters.granulometryRange * config.RBCRadiusByResolution.Pixel
68 int <| config.RBCRadiusByResolution.Pixel - delta, int <| config.RBCRadiusByResolution.Pixel + delta
69
70 let! radius = logTimeWithName "Granulometry (area)" (fun () -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing img_RBC_filtered range |> float32))
71 //let! radius = logTimeWithName "Granulometry (morpho)" (fun () -> reportWithVal 10 (Granulometry.findRadiusByClosing img_RBC_filtered range 1. true |> float32))
72 config.SetRBCRadius <| radius
73
74 logWithName (sprintf "Found erythrocyte diameter: %O" config.RBCRadius)
75
76 do! report 20
77
78 do!
79 let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
80 if secondAreaOpening > initialAreaOpening then
81 logTimeWithName "Second area opening" (fun () -> areaOpenF img_RBC_filtered secondAreaOpening; report 30)
82 else
83 report 30
84
85 // Remove pale centers from the parasites image.
86 areaOpenF img_parasites_filtered (int <| config.RBCRadiusByResolution.Area * config.Parameters.ratioAreaPaleCenter)
87
88 // Removing parasites.
89 areaCloseF img_RBC_filtered (roundInt <| Const.PI * config.RBCRadius.ParasiteRadius ** 2.f)
90
91 let! parasites, imgWhitoutParasite, imgWithoutNucleus =
92 logTimeWithName "Parasites segmentation" (fun () -> reportWithVal 40 (ParasitesMarker.find img_parasites_filtered config))
93
94 let! edges, xGradient, yGradient =
95 logTimeWithName "Finding edges" (
96 fun () ->
97 let edges, xGradient, yGradient = Edges.find img_RBC_filtered
98 removeArea edges (config.RBCRadius.Pixel ** 2.f / 50.f |> int)
99 reportWithVal 50 (edges, xGradient, yGradient)
100 )
101
102 let! matchingEllipses = logTimeWithName "Finding ellipses" (fun () -> reportWithVal 60 (Ellipse.find edges xGradient yGradient config))
103
104 let! prunedEllipses = logTimeWithName "Ellipses pruning" (fun () -> reportWithVal 80 (matchingEllipses.PrunedEllipses))
105
106 let! cells = logTimeWithName "Classifier" (fun () -> reportWithVal 100 (Classifier.findCells prunedEllipses parasites img.Width img.Height config))
107
108 do
109 if config.RBCRadiusByResolution.μm / config.RBCRadius.μm > warningRatioDifferenceRBCDiameter then
110 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)
111 elif config.RBCRadius.μm / config.RBCRadiusByResolution.μm > warningRatioDifferenceRBCDiameter then
112 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)
113
114 logWithName "Analysis finished"
115
116 do
117 // Output pictures if debug flag is set.
118 match config.Debug with
119 | DebugOn output ->
120 let dirPath = System.IO.Path.Combine (output, name)
121 System.IO.Directory.CreateDirectory dirPath |> ignore
122
123 let buildFileName postfix = System.IO.Path.Combine (dirPath, name + postfix)
124
125 IO.saveMat (edges * 255.0) (buildFileName " - edges.png")
126
127 IO.saveImg parasites.darkStain (buildFileName " - parasites - dark stain.png")
128 IO.saveImg parasites.parasite (buildFileName " - parasites - stain.png")
129 IO.saveImg parasites.nucleus (buildFileName " - parasites - infection.png")
130
131 let imgAllEllipses = img_RBC_filtered.Copy ()
132 Drawing.drawEllipses imgAllEllipses matchingEllipses.Ellipses (Gray 200.0) 0.04
133 IO.saveImg imgAllEllipses (buildFileName " - ellipses - all.png")
134
135 let imgEllipses = img_RBC_filtered.Convert<Bgr, byte> ()
136 Drawing.drawEllipses imgEllipses prunedEllipses (Bgr (0.0, 240.0, 240.0)) 1.0
137 IO.saveImg imgEllipses (buildFileName " - ellipses.png")
138
139 let imgCells = img.Copy ()
140 Drawing.drawCells imgCells false cells
141 IO.saveImg imgCells (buildFileName " - cells.png")
142
143 let imgCells' = img.Copy ()
144 Drawing.drawCells imgCells' true cells
145 IO.saveImg imgCells' (buildFileName " - cells - full.png")
146
147 (* let filteredRBCMaxima = gaussianFilter img_RBC config.LPFStandardDeviationRBC
148 for m in findMaxima filteredRBCMaxima do
149 Drawing.drawPoints filteredRBCMaxima m 255.f
150 IO.saveImg filteredRBCMaxima (buildFileName " - filtered - maxima.png") *)
151
152 IO.saveImg imgWhitoutParasite (buildFileName " - filtered closed stain.png")
153 IO.saveImg imgWithoutNucleus (buildFileName " - filtered closed infection.png")
154
155 IO.saveImg img_RBC_filtered (buildFileName " - source - RBC.png")
156 IO.saveImg img_parasites_filtered (buildFileName " - source - parasites.png")
157
158 IO.saveImg img_float.[2] (buildFileName " - source - red.png")
159 IO.saveImg img_float.[1] (buildFileName " - source - green.png")
160 IO.saveImg img_float.[0] (buildFileName " - source - blue.png")
161 | _ -> ()
162
163 return
164 {
165 Cells = cells
166 RBCSize_μm = config.RBCRadius.μm
167 RBCSize_px = config.RBCRadius.Pixel
168 }
169
170 //return cells
171 }
172
173 /// <summary>
174 /// Do multiple analyses on the same time. The number of concurrent process depends on the number of the core.
175 /// </summary>
176 /// <param name="imgs">The images: (name * configuration * image)</param>
177 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
178 /// The first call returning 'false' will cancel the analysis.
179 /// The 'int' parameter correspond to the progression from 0 to 100</param>
180 /// <return>'None' if the process has been cancelled or the list of result as (name * cells), 'name' corresponds to the given name</return>
181 let doMultipleAnalysis (imgs : (string * Config * Image<Bgr, byte>) list) (reportProgress : (int -> bool) option) : (string * AnalysisResult) list option =
182 let report (percent : int) : bool =
183 match reportProgress with
184 | Some f -> f percent
185 | _ -> true
186
187 let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int> ()
188 let nbImgs = List.length imgs
189
190 let reportProgressImg (id : string) (progress : int) =
191 progressPerAnalysis.AddOrUpdate (id, progress, (fun _ _ -> progress)) |> ignore
192 report (progressPerAnalysis.Values.Sum () / nbImgs)
193
194 let n = Environment.ProcessorCount
195
196 let results =
197 imgs
198 |> PSeq.choose (
199 fun (id, config, img) ->
200 try
201 match doAnalysis img id config (Some (fun p -> reportProgressImg id p)) with
202 | Some result -> Some (id, result)
203 | None -> None
204 with
205 | ex ->
206 Log.Error "Analysis %s failed: %O" id ex
207 None
208 )
209 |> PSeq.withDegreeOfParallelism n
210 |> PSeq.toList
211
212 // If one of the analyses has been aborted we return 'None'.
213 if List.length results <> List.length imgs then
214 None
215 else
216 Some results
217