Project the colors to have the best contrast for RBCs and parasites analyze.
[master-thesis.git] / Parasitemia / ParasitemiaCore / MainAnalysis.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 ImgTools
16 open Config
17 open Types
18
19 /// <summary>
20 /// Analyze the given image and detect reb blood cell (RBC) in it.
21 /// </summary>
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 =
30
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
35 | Some f ->
36 if f percent
37 then Some value
38 else None
39 | _ -> Some value
40
41 let report (percent: int) : unit option =
42 reportWithVal percent ()
43
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)
47
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 = mergeChannels img_float config.Parameters.colorContribution_BG_RBC
56 use img_RBC = mergeChannelsWithProjection img_float (94.7f, 80.7f, 99.3f) (113.3f, 135.3f, 150.3f) 255.
57 let img_RBC_filtered = gaussianFilter img_RBC config.LPFStandardDeviationRBC
58
59 //use img_parasites = mergeChannels img_float config.Parameters.colorContribution_RBC_parasite
60 use img_parasites = mergeChannelsWithProjection img_float (76.f, 58.f, 94.f) (94.7f, 80.7f, 99.3f) 255.
61
62 logWithName (sprintf "Nominal erytrocyte diameter: %A" config.RBCRadiusByResolution)
63
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 () -> ImgTools.areaOpenF img_RBC_filtered initialAreaOpening; report 10)
66
67 let range =
68 let delta = config.Parameters.granulometryRange * config.RBCRadiusByResolution.Pixel
69 int <| config.RBCRadiusByResolution.Pixel - delta, int <| config.RBCRadiusByResolution.Pixel + delta
70 //let r1 = log "Granulometry (morpho)" (fun() -> Granulometry.findRadiusByClosing (filteredGreen.Convert<Gray, byte>()) range 1.0 |> float32)
71 let! radius = logTimeWithName "Granulometry (area)" (fun() -> reportWithVal 10 (Granulometry.findRadiusByAreaClosing img_RBC_filtered range |> float32))
72 config.SetRBCRadius <| radius
73
74 logWithName (sprintf "Found erytrocyte diameter: %A" config.RBCRadius)
75
76 do! report 20
77
78 do!
79 let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
80 if secondAreaOpening > initialAreaOpening
81 then
82 logTimeWithName "Second area opening" (fun () -> ImgTools.areaOpenF img_RBC_filtered secondAreaOpening; report 30)
83 else
84 report 30
85
86 // Removing of parasites.
87 ImgTools.areaCloseF img_RBC_filtered (roundInt <| Const.PI * config.RBCRadius.ParasiteRadius ** 2.f)
88
89 let parasites, filteredGreenWhitoutStain, filteredGreenWithoutInfection = ParasitesMarker.find img_parasites config
90 //let parasites, filteredGreenWhitoutInfection, filteredGreenWhitoutStain = ParasitesMarker.findMa greenFloat filteredGreenFloat config
91
92 let! edges, xGradient, yGradient = logTimeWithName "Finding edges" (fun () ->
93 let edges, xGradient, yGradient = ImgTools.findEdges img_RBC_filtered
94 removeArea edges (config.RBCRadius.Pixel ** 2.f / 50.f |> int)
95 reportWithVal 40 (edges, xGradient, yGradient))
96
97 let! matchingEllipses = logTimeWithName "Finding ellipses" (fun () -> reportWithVal 60 (Ellipse.find edges xGradient yGradient config))
98
99 let! prunedEllipses = logTimeWithName "Ellipses pruning" (fun () -> reportWithVal 80 (matchingEllipses.PrunedEllipses))
100
101 let! cells = logTimeWithName "Classifier" (fun () -> reportWithVal 100 (Classifier.findCells prunedEllipses parasites img_RBC_filtered config))
102
103 logWithName "Analysis finished"
104
105 do
106 // Output pictures if debug flag is set.
107 match config.Debug with
108 | DebugOn output ->
109 let dirPath = System.IO.Path.Combine(output, name)
110 System.IO.Directory.CreateDirectory dirPath |> ignore
111
112 let buildFileName postfix = System.IO.Path.Combine(dirPath, name + postfix)
113
114 saveMat (edges * 255.0) (buildFileName " - edges.png")
115
116 saveImg parasites.darkStain (buildFileName " - parasites - dark stain.png")
117 saveImg parasites.stain (buildFileName " - parasites - stain.png")
118 saveImg parasites.infection (buildFileName " - parasites - infection.png")
119
120 let imgAllEllipses = img.Copy()
121 drawEllipses imgAllEllipses matchingEllipses.Ellipses (Bgr(255.0, 255.0, 255.0)) 0.04
122 saveImg imgAllEllipses (buildFileName " - ellipses - all.png")
123
124 let imgEllipses = img_RBC_filtered.Convert<Bgr, byte>()
125 drawEllipses imgEllipses prunedEllipses (Bgr(0.0, 240.0, 240.0)) 1.0
126 saveImg imgEllipses (buildFileName " - ellipses.png")
127
128 let imgCells = img.Copy()
129 drawCells imgCells false cells
130 saveImg imgCells (buildFileName " - cells.png")
131
132 let imgCells' = img.Copy()
133 drawCells imgCells' true cells
134 saveImg imgCells' (buildFileName " - cells - full.png")
135
136 let filteredGreenMaxima = gaussianFilter img_RBC config.LPFStandardDeviationRBC
137 for m in ImgTools.findMaxima filteredGreenMaxima do
138 ImgTools.drawPoints filteredGreenMaxima m 255.f
139 saveImg filteredGreenMaxima (buildFileName " - filtered - maxima.png")
140
141 saveImg img_RBC_filtered (buildFileName " - filtered.png")
142 saveImg filteredGreenWhitoutStain (buildFileName " - filtered closed stain.png")
143 saveImg filteredGreenWithoutInfection (buildFileName " - filtered closed infection.png")
144
145 saveImg img_RBC (buildFileName " - source - RBC.png")
146 saveImg img_parasites (buildFileName " - source - parasites.png")
147 | _ -> ()
148
149 return cells }
150
151 /// <summary>
152 /// Do multiple analyses on the same time. The number of concurrent process depends if the number of the core.
153 /// </summary>
154 /// <param name="imgs">The images: (name * configuration * image)</param>
155 /// <param name="reportProgress">An optional function to report progress and/or cancel the process.
156 /// The first call returning 'false' will cancel the analysis.
157 /// The 'int' parameter correspond to the progression from 0 to 100</param>
158 /// <returns>'None' if the process has been cancelled or the list of result as (name * cells), 'name' corresponds to the given name<returns>
159 let doMultipleAnalysis (imgs: (string * Config * Image<Bgr, byte>) list) (reportProgress: (int -> bool) option) : (string * Cell list) list option =
160 let report (percent: int) : bool =
161 match reportProgress with
162 | Some f -> f percent
163 | _ -> true
164
165 let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int>()
166 let nbImgs = List.length imgs
167
168 let reportProgressImg (id: string) (progress: int) =
169 progressPerAnalysis.AddOrUpdate(id, progress, (fun _ _ -> progress)) |> ignore
170 report (progressPerAnalysis.Values.Sum() / nbImgs)
171
172 let n = Environment.ProcessorCount
173
174 let results =
175 imgs
176 |> PSeq.choose (
177 fun (id, config, img) ->
178 match doAnalysis img id config (Some (fun p -> reportProgressImg id p)) with
179 | Some result -> Some (id, result)
180 | None -> None)
181 |> PSeq.withDegreeOfParallelism n
182 |> PSeq.toList
183
184 // If one of the analyses has been aborted we return 'None'.
185 if List.length results <> List.length imgs
186 then None
187 else Some results
188