1822c75dc2221c0c7775f582c2c4700483ed086c
[master-thesis.git] / Parasitemia / Parasitemia / KMedians.fs
1 module KMedians
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 median_bg: float
12 median_fg: float
13 d_fg: Image<Gray, float32> } // Distances to median_fg.
14
15 let kmedians (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 median_bg = (!max).[0] - ((!max).[0] - (!min).[0]) / 4.0
27 let mutable median_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 CvInvoke.Pow(img - median_bg, 2.0, d_bg)
34 CvInvoke.Pow(img - median_fg, 2.0, d_fg)
35 fg <- (d_fg * fgFactor).Cmp(d_bg, CvEnum.CmpType.LessThan)
36
37 median_fg <- MathNet.Numerics.Statistics.Statistics.Median(seq {
38 for i in 0 .. h - 1 do
39 for j in 0 .. w - 1 do
40 if fg.Data.[i, j, 0] > 0uy then yield img.Data.[i, j, 0] |> float })
41
42 median_bg <- MathNet.Numerics.Statistics.Statistics.Median(seq {
43 for i in 0 .. h - 1 do
44 for j in 0 .. w - 1 do
45 if fg.Data.[i, j, 0] = 0uy then yield img.Data.[i, j, 0] |> float })
46
47 CvInvoke.Sqrt(d_fg, d_fg)
48
49 { fg = fg; median_bg = median_bg; median_fg = median_fg; d_fg = d_fg }
50
51
52
53