/
Thresholds.go
116 lines (92 loc) · 2.59 KB
/
Thresholds.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package ImageTools
import (
"sync"
)
/*
* Thresholds an image with a single threshold
*/
func SingleThreshold(image [][]float32, threshold float32) [][]float32 {
imageWidth, imageHeight := Dimensions(image)
// Create output image
outputImage := make([][]float32, imageWidth)
for j := range outputImage {
outputImage[j] = make([]float32, imageHeight)
}
// Create wait group
var waitGroup sync.WaitGroup
if imageWidth > imageHeight {
waitGroup.Add(imageWidth)
} else {
waitGroup.Add(imageHeight)
}
// Iterate over columns
for j := 0; j < imageHeight; j++ {
// Process each row on its own goroutine
go func(j int) {
defer waitGroup.Done()
// Iterate over row
for i := 0; i < imageWidth; i++ {
// Apply threshold to each pixel
currentPixel := image[i][j]
if currentPixel < threshold {
outputImage[i][j] = 0
} else {
outputImage[i][j] = 1
}
}
} (j)
}
return outputImage
}
/*
* Thresholds an image with 2 thresholds
* White pixel if it's between the thresholds, otherwise black
*/
func DualThreshold(image [][]float32, thresholdA float32, thresholdB float32) [][]float32 {
imageWidth, imageHeight := Dimensions(image)
// Find which threshold is the upper one and which is the lower one
upperThreshold, lowerThreshold := float32(thresholdA), float32(thresholdB)
if thresholdA < thresholdB {
upperThreshold, lowerThreshold = float32(thresholdB), float32(thresholdA)
}
// Create output image
outputImage := make([][]float32, imageWidth)
for j := range outputImage {
outputImage[j] = make([]float32, imageHeight)
}
// Create wait group
var waitGroup sync.WaitGroup
if imageWidth > imageHeight {
waitGroup.Add(imageWidth)
} else {
waitGroup.Add(imageHeight)
}
// Iterate over columns
for j := 0; j < imageHeight; j++ {
// Process each row on its own goroutine
go func(j int) {
defer waitGroup.Done()
// Iterate over row
for i := 0; i < imageWidth; i++ {
// Apply thresholds to each pixel
currentPixel := image[i][j]
if currentPixel < upperThreshold && currentPixel > lowerThreshold {
outputImage[i][j] = 1
} else {
outputImage[i][j] = 0
}
}
} (j)
}
return outputImage
}
func HysteresisThreshold(image [][]float32, thresholdA float32, thresholdB float32) [][]float32 {
// Find which threshold is the upper one and which is the lower one
upperThreshold, lowerThreshold := float64(thresholdA), float64(thresholdB)
if thresholdA < thresholdB {
upperThreshold, lowerThreshold = float64(thresholdB), float64(thresholdA)
}
//Delete this line
upperThreshold += lowerThreshold
return image
}