7c18120b65fe76bccab00288a983a311fc4651ef
[master-thesis.git] / Parasitemia / Parasitemia / KMeans.fs
1 module KMeans
2
3 open System.Collections.Generic
4 open System.Drawing
5
6 open Emgu.CV
7 open Emgu.CV.Structure
8
9 type Result = {
10 fg: Image<Gray, byte>
11 mean_bg: float
12 mean_fg: float
13 d_fg: Image<Gray, float32> } // Euclidean distances of the foreground to mean_fg.
14
15 let kmeans (img: Image<Gray, float32>) (fgFactor: float) : Result =
16 let nbIteration = 3
17 let w = img.Width
18 let h = img.Height
19
20 let min = ref [| 0.0 |]
21 let minLocation = ref <| [| Point() |]
22 let max = ref [| 0.0 |]
23 let maxLocation = ref <| [| Point() |]
24 img.MinMax(min, max, minLocation, maxLocation)
25
26 let mutable mean_bg = (!max).[0] - ((!max).[0] - (!min).[0]) / 4.0
27 let mutable mean_fg = (!min).[0] + ((!max).[0] - (!min).[0]) / 4.0
28 use mutable d_bg = new Image<Gray, float32>(img.Size)
29 let mutable d_fg = new Image<Gray, float32>(img.Size)
30 let mutable fg = new Image<Gray, byte>(img.Size)
31
32 for i in 1 .. nbIteration do
33 d_bg <- img.AbsDiff(Gray(mean_bg))
34 d_fg <- img.AbsDiff(Gray(mean_fg))
35
36 CvInvoke.Compare(d_fg, d_bg, fg, CvEnum.CmpType.LessThan)
37
38 let mutable bg_total = 0.0
39 let mutable bg_nb = 0
40
41 let mutable fg_total = 0.0
42 let mutable fg_nb = 0
43
44 for i in 0 .. h - 1 do
45 for j in 0 .. w - 1 do
46 if fg.Data.[i, j, 0] > 0uy
47 then
48 fg_total <- fg_total + float img.Data.[i, j, 0]
49 fg_nb <- fg_nb + 1
50 else
51 bg_total <- bg_total + float img.Data.[i, j, 0]
52 bg_nb <- bg_nb + 1
53
54 mean_bg <- bg_total / float bg_nb
55 mean_fg <- fg_total / float fg_nb
56
57 { fg = fg; mean_bg = mean_bg; mean_fg = mean_fg; d_fg = d_fg }