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