Split the module 'ImgTools' in many modules.
[master-thesis.git] / Parasitemia / ParasitemiaCore / Granulometry.fs
1 module ParasitemiaCore.Granulometry
2
3 open System
4 open System.Drawing
5
6 open Emgu.CV
7 open Emgu.CV.Structure
8
9 open Utils
10
11 /// <summary>
12 /// Granulometry by closing on the image 'img' by testing circle structrual elements with radius range in 'range'.
13 /// </summary>
14 /// <param name="img"></param>
15 /// <param name="range">Minimum radius * maximum radius</param>
16 /// <param name="scale">le 1.0, to speed up the process.</param>
17 let findRadiusByClosing (img: Image<Gray, 'TDepth>) (range: int * int) (scale: float) (useOctagon: bool) : int =
18 use scaledImg = if scale = 1. then img else img.Resize(scale, CvEnum.Inter.Area)
19
20 let r1, r2 = range
21 let r1', r2' = roundInt (float r1 * scale), roundInt (float r2 * scale)
22
23 let patternSpectrum = Array.zeroCreate (r2' - r1')
24 let intensityImg = scaledImg.GetSum().Intensity
25
26 // 's' must be odd.
27 let octagon (s: int) : Mat =
28 if s % 2 = 0 then failwith "s must be odd"
29 let m = new Matrix<byte>(Array2D.create s s 1uy)
30 let r = (float s) / (Math.Sqrt 2. + 2.) |> roundInt
31 for i in 0 .. r - 1 do
32 for j in 0 .. r - 1 do
33 if i + j < r
34 then
35 m.[i, j] <- 0uy
36 m.[s - i - 1, j] <- 0uy
37 m.[i, s - j - 1] <- 0uy
38 m.[s - i - 1, s - j - 1] <- 0uy
39 m.Mat
40
41 let mutable previous_n = Double.NaN
42 for r in r1' .. r2' do
43 let se = if useOctagon
44 then octagon (2 * r - 1) // It doesnd't speed up the process.
45 else CvInvoke.GetStructuringElement(CvEnum.ElementShape.Ellipse, Size(2 * r, 2 * r), Point(-1, -1))
46
47 use closed = scaledImg.MorphologyEx(CvEnum.MorphOp.Close, se, Point(-1, -1), 1, CvEnum.BorderType.Replicate, MCvScalar(0.0))
48
49 let n = closed.GetSum().Intensity
50
51 if not (Double.IsNaN previous_n)
52 then
53 patternSpectrum.[r - r1' - 1] <- abs (n - previous_n)
54 previous_n <- n
55
56 let max, _ = patternSpectrum |> Array.indexed |> Array.fold (fun (iMax, sMax) (i, s) -> if s > sMax then (i, s) else (iMax, sMax)) (0, Double.MinValue)
57
58 float (max + r1') / scale |> roundInt
59
60 /// <summary>
61 /// Granulometry by area closing on the image 'img' by testing the circle area into the given radius range.
62 /// </summary>
63 let findRadiusByAreaClosing (img: Image<Gray, float32>) (radiusRange: int * int) : int =
64 let r1, r2 = radiusRange
65
66 if r1 > r2
67 then failwithf "'radiusRange' invalid : %A" radiusRange
68
69 use imgCopy = img.Copy()
70
71 let mutable maxDiff = 0.f
72 let mutable max_r = r1
73
74 Morpho.areaCloseFWithFun imgCopy [ for r in r1 .. r2 -> Math.PI * float r ** 2. |> roundInt, r ] (fun r diff ->
75 if r <> r1 && diff > maxDiff
76 then
77 maxDiff <- diff
78 max_r <- r - 1)
79 max_r
80