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