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