Use two radius in the configuration, one computed with the image resolution and one...
[master-thesis.git] / Parasitemia / Parasitemia / MainAnalysis.fs
1 module ImageAnalysis
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 Utils
13 open ImgTools
14 open Config
15 open Types
16
17 let doAnalysis (img: Image<Bgr, byte>) (name: string) (config: Config) (reportProgress: (int -> unit) option) : Cell list =
18 // To report the progress of this function from 0 to 100.
19 let inline report (percent: int) =
20 match reportProgress with
21 | Some f -> f percent
22 | _ -> ()
23
24 let inline buildLogWithName (text: string) = sprintf "(%s) %s" name text
25 let logWithName = buildLogWithName >> log
26 let inline logTimeWithName (text: string) (f: unit -> 'a) : 'a = logTime (buildLogWithName text) f
27
28 logWithName "Starting analysis ..."
29
30 use green = img.Item(1)
31 let greenFloat = green.Convert<Gray, float32>()
32 let filteredGreen = gaussianFilter greenFloat config.LPFStandardDeviation
33
34 logWithName (sprintf "Nominal erytrocyte diameter: %A" config.RBCRadiusByResolution)
35
36 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.
37 logTimeWithName "Area opening number one" (fun () -> ImgTools.areaOpenF filteredGreen initialAreaOpening)
38
39 report 8
40
41 let range =
42 let delta = config.Parameters.granulometryRange * config.RBCRadiusByResolution.Pixel
43 int <| config.RBCRadiusByResolution.Pixel - delta, int <| config.RBCRadiusByResolution.Pixel + delta
44 //let r1 = log "Granulometry (morpho)" (fun() -> Granulometry.findRadiusByClosing (filteredGreen.Convert<Gray, byte>()) range 1.0 |> float32)
45 config.SetRBCRadius <| logTimeWithName "Granulometry (area)" (fun() -> Granulometry.findRadiusByAreaClosing filteredGreen range |> float32)
46 // log (sprintf "r1: %A, r2: %A" r1 r2)
47
48 logWithName (sprintf "Found erytrocyte diameter: %A" config.RBCRadius)
49
50 report 24
51
52 let secondAreaOpening = int <| config.RBCRadius.Area * config.Parameters.ratioAreaPaleCenter
53 if secondAreaOpening > initialAreaOpening
54 then
55 logTimeWithName "Area opening number two" (fun () -> ImgTools.areaOpenF filteredGreen secondAreaOpening)
56
57 let parasites, filteredGreenWhitoutStain = ParasitesMarker.find filteredGreen config
58 //let parasites, filteredGreenWhitoutInfection, filteredGreenWhitoutStain = ParasitesMarker.findMa greenFloat filteredGreenFloat config
59
60 let edges, xGradient, yGradient = logTimeWithName "Finding edges" (fun () ->
61 let edges, xGradient, yGradient = ImgTools.findEdges filteredGreenWhitoutStain
62 removeArea edges (config.RBCRadius.Pixel ** 2.f / 50.f |> int)
63 edges, xGradient, yGradient)
64
65 let allEllipses, ellipses = logTimeWithName "Finding ellipses" (fun () ->
66 let matchingEllipses = Ellipse.find edges xGradient yGradient config
67 matchingEllipses.Ellipses, matchingEllipses.PrunedEllipses)
68
69 report 80
70
71 let cells = logTimeWithName "Classifier" (fun () -> Classifier.findCells ellipses parasites filteredGreenWhitoutStain config)
72
73 report 100
74
75 logWithName "Analysis finished"
76
77 // Output pictures if debug flag is set.
78 match config.Debug with
79 | DebugOn output ->
80 let dirPath = System.IO.Path.Combine(output, name)
81 System.IO.Directory.CreateDirectory dirPath |> ignore
82
83 let buildFileName postfix = System.IO.Path.Combine(dirPath, name + postfix)
84
85 saveMat (edges * 255.0) (buildFileName " - edges.png")
86
87 saveImg parasites.darkStain (buildFileName " - parasites - dark stain.png")
88 saveImg parasites.stain (buildFileName " - parasites - stain.png")
89 saveImg parasites.infection (buildFileName " - parasites - infection.png")
90
91 let imgAllEllipses = img.Copy()
92 drawEllipses imgAllEllipses allEllipses (Bgr(0.0, 240.0, 240.0)) 0.05
93 saveImg imgAllEllipses (buildFileName " - ellipses - all.png")
94
95 let imgEllipses = filteredGreenWhitoutStain.Convert<Bgr, byte>()
96 drawEllipses imgEllipses ellipses (Bgr(0.0, 240.0, 240.0)) 1.0
97 saveImg imgEllipses (buildFileName " - ellipses.png")
98
99 let imgCells = img.Copy()
100 drawCells imgCells false cells
101 saveImg imgCells (buildFileName " - cells.png")
102
103 let imgCells' = img.Copy()
104 drawCells imgCells' true cells
105 saveImg imgCells' (buildFileName " - cells - full.png")
106
107 let filteredGreenMaxima = gaussianFilter greenFloat config.LPFStandardDeviation
108 for m in ImgTools.findMaxima filteredGreenMaxima do
109 ImgTools.drawPoints filteredGreenMaxima m 255.f
110 saveImg filteredGreenMaxima (buildFileName " - filtered - maxima.png")
111
112 saveImg filteredGreen (buildFileName " - filtered.png")
113 saveImg filteredGreenWhitoutStain (buildFileName " - filtered closed stain.png")
114 //saveImg filteredGreenWhitoutInfection (buildFileName " - filtered closed infection.png")
115
116 saveImg green (buildFileName " - green.png")
117
118 use blue = img.Item(0)
119 saveImg blue (buildFileName " - blue.png")
120
121 use red = img.Item(2)
122 saveImg red (buildFileName " - red.png")
123 | _ -> ()
124
125 cells
126
127 // ID * cell list.
128 let doMultipleAnalysis (imgs: (string * Config * Image<Bgr, byte>) list) (reportProgress: (int -> unit) option) : (string * Cell list) list =
129 let inline report (percent: int) =
130 match reportProgress with
131 | Some f -> f percent
132 | _ -> ()
133
134 let progressPerAnalysis = System.Collections.Concurrent.ConcurrentDictionary<string, int>()
135 let nbImgs = List.length imgs
136
137 let reportProgressImg (id: string) (progress: int) =
138 progressPerAnalysis.AddOrUpdate(id, progress, (fun _ _ -> progress)) |> ignore
139 report (progressPerAnalysis.Values.Sum() / nbImgs)
140
141 let nbConcurrentTaskLimit = 4 // To reduce the memory taken.
142 let n = Environment.ProcessorCount
143
144 imgs
145 |> PSeq.map (fun (id, config, img) -> id, doAnalysis img id config (Some (fun p -> reportProgressImg id p)))
146 |> PSeq.withDegreeOfParallelism (if n > nbConcurrentTaskLimit then nbConcurrentTaskLimit else n)
147 |> PSeq.toList