Save imported image in the same format (WIP)
[master-thesis.git] / ParasitemiaCore / ImgTools / Histogram.fs
1 module ParasitemiaCore.Histogram
2
3 open System
4 open System.Drawing
5
6 open Emgu.CV
7 open Emgu.CV.Structure
8
9 type Histogram =
10 {
11 data : int[]
12 total : int // Number of elements.
13 sum : int // Sum of all intensity.
14 min : float32
15 max : float32
16 }
17
18 let histogramImg (img : Image<Gray, float32>) (nbSamples : int) : Histogram =
19 let imgData = img.Data
20
21 let min, max =
22 let min = ref [| 0.0 |]
23 let minLocation = ref <| [| Point() |]
24 let max = ref [| 0.0 |]
25 let maxLocation = ref <| [| Point() |]
26 img.MinMax(min, max, minLocation, maxLocation)
27 float32 (!min).[0], float32 (!max).[0]
28
29 let inline bin (x : float32) : int =
30 let p = int ((x - min) / (max - min) * float32 nbSamples)
31 if p >= nbSamples then nbSamples - 1 else p
32
33 let data = Array.zeroCreate nbSamples
34
35 for i = 0 to img.Height - 1 do
36 for j = 0 to img.Width - 1 do
37 let p = bin imgData.[i, j, 0]
38 data.[p] <- data.[p] + 1
39
40 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
41
42 let histogramMat (mat : Matrix<float32>) (nbSamples : int) : Histogram =
43 let matData = mat.Data
44
45 let min, max =
46 let min = ref 0.0
47 let minLocation = ref <| Point()
48 let max = ref 0.0
49 let maxLocation = ref <| Point()
50 mat.MinMax(min, max, minLocation, maxLocation)
51 float32 !min, float32 !max
52
53 let inline bin (x : float32) : int =
54 let p = int ((x - min) / (max - min) * float32 nbSamples)
55 if p >= nbSamples then nbSamples - 1 else p
56
57 let data = Array.zeroCreate nbSamples
58
59 for i = 0 to mat.Height - 1 do
60 for j = 0 to mat.Width - 1 do
61 let p = bin matData.[i, j]
62 data.[p] <- data.[p] + 1
63
64 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
65
66 let histogram (values : float32 seq) (nbSamples : int) : Histogram =
67 let mutable min = Single.MaxValue
68 let mutable max = Single.MinValue
69 let mutable n = 0
70
71 for v in values do
72 n <- n + 1
73 if v < min then min <- v
74 if v > max then max <- v
75
76 let inline bin (x : float32) : int =
77 let p = int ((x - min) / (max - min) * float32 nbSamples)
78 if p >= nbSamples then nbSamples - 1 else p
79
80 let data = Array.zeroCreate nbSamples
81
82 for v in values do
83 let p = bin v
84 data.[p] <- data.[p] + 1
85
86 { data = data; total = n; sum = Array.sum data; min = min; max = max }