-
Notifications
You must be signed in to change notification settings - Fork 16
/
threshold.go
52 lines (37 loc) · 858 Bytes
/
threshold.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// gOCR - Automatic Thresholding Module
package main
import (
"gocv.io/x/gocv"
)
func getAvgIn(hist []int, lb int) int {
sum := 0
count := 0
for i := range hist {
count += hist[i]
sum += (lb + i) * hist[i]
}
return sum / count
}
// Automatic threshold algorithm
func getThresholdValue(img gocv.Mat) float32 {
hist := GetHistArray(img)
t := getAvgIn(hist, 0)
ou1, ou2 := 0, 0
u1, u2 := 255, 255
for {
u1 = getAvgIn(hist[:t], 0)
u2 = getAvgIn(hist[t:], t-1)
t = (u1 + u2) / 2
if u1 == ou1 && u2 == ou2 {
break
}
ou1, ou2 = u1, u2
}
return float32(t)
}
// AutoThreshold - Return Apply Auto Threshold
func AutoThreshold(img gocv.Mat) gocv.Mat {
imgOut := gocv.NewMatWithSize(img.Rows(), img.Cols(), gocv.MatTypeCV8U)
gocv.Threshold(img, imgOut, getThresholdValue(img), 255, gocv.ThresholdBinary)
return imgOut
}