82dfde4e9b718336f7789654217c44f338455970
[master-thesis.git] / Parasitemia / ParasitemiaCore / ImgTools / Otsu.fs
1 module ParasitemiaCore.Otsu
2
3 open Histogram
4
5 let otsu (hist: Histogram) : float32 * float32 * float32 =
6 let mutable sumB = 0
7 let mutable wB = 0
8 let mutable maximum = 0.0
9 let mutable level = 0
10 let sum = hist.data |> Array.mapi (fun i v -> i * v |> float) |> Array.sum
11
12 for i = 0 to hist.data.Length - 1 do
13 wB <- wB + hist.data.[i]
14 if wB <> 0
15 then
16 let wF = hist.total - wB
17 if wF <> 0
18 then
19 sumB <- sumB + i * hist.data.[i]
20 let mB = (float sumB) / (float wB)
21 let mF = (sum - float sumB) / (float wF)
22 let between = (float wB) * (float wF) * (mB - mF) ** 2.;
23 if between >= maximum
24 then
25 level <- i
26 maximum <- between
27
28 let mean1 =
29 let mutable sum = 0
30 let mutable nb = 0
31 for i = 0 to level - 1 do
32 sum <- sum + i * hist.data.[i]
33 nb <- nb + hist.data.[i]
34 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
35
36 let mean2 =
37 let mutable sum = 0
38 let mutable nb = 0
39 for i = level + 1 to hist.data.Length - 1 do
40 sum <- sum + i * hist.data.[i]
41 nb <- nb + hist.data.[i]
42 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
43
44 let toFloat l =
45 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
46
47 toFloat level, toFloat mean1, toFloat mean2