Add a logger assembly and split the main assembly in two : the UI and the parasitemia...
[master-thesis.git] / Parasitemia / ParasitemiaCore / KMedians.fs
diff --git a/Parasitemia/ParasitemiaCore/KMedians.fs b/Parasitemia/ParasitemiaCore/KMedians.fs
new file mode 100644 (file)
index 0000000..5819a66
--- /dev/null
@@ -0,0 +1,54 @@
+module ParasitemiaCore.KMedians
+
+open System.Collections.Generic
+open System.Drawing
+
+open Emgu.CV
+open Emgu.CV.Structure
+
+type Result = {
+    fg: Image<Gray, byte>
+    median_bg: float
+    median_fg: float
+    d_fg: Image<Gray, float32> } // Euclidean distances of the foreground to median_fg.
+
+let kmedians (img: Image<Gray, float32>) : Result =
+    let nbIteration = 4
+    let w = img.Width
+    let h = img.Height
+
+    let min = ref [| 0.0 |]
+    let minLocation = ref <| [| Point() |]
+    let max = ref [| 0.0 |]
+    let maxLocation = ref <| [| Point() |]
+    img.MinMax(min, max, minLocation, maxLocation)
+
+    let mutable median_bg = (!max).[0] - ((!max).[0] - (!min).[0]) / 4.0
+    let mutable median_fg = (!min).[0] + ((!max).[0] - (!min).[0]) / 4.0
+    use mutable d_bg = new Image<Gray, float32>(img.Size)
+    let mutable d_fg = new Image<Gray, float32>(img.Size)
+    let mutable fg = new Image<Gray, byte>(img.Size)
+
+    for i in 1 .. nbIteration do
+        d_bg <- img.AbsDiff(Gray(median_bg))
+        d_fg <- img.AbsDiff(Gray(median_fg))
+
+        CvInvoke.Compare(d_fg, d_bg, fg, CvEnum.CmpType.LessThan)
+
+        let bg_values = List<float>()
+        let fg_values = List<float>()
+
+        for i in 0 .. h - 1 do
+            for j in 0 .. w - 1 do
+                if fg.Data.[i, j, 0] > 0uy
+                then fg_values.Add(float img.Data.[i, j, 0])
+                else bg_values.Add(float img.Data.[i, j, 0])
+
+        median_bg <- MathNet.Numerics.Statistics.Statistics.Median(bg_values)
+        median_fg <- MathNet.Numerics.Statistics.Statistics.Median(fg_values)
+
+    { fg = fg; median_bg = median_bg; median_fg = median_fg; d_fg = d_fg }
+
+
+
+