-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
85 lines (71 loc) · 1.72 KB
/
utils.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
package rainfall
import (
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
)
func make2DMatrix(width, height int) [][]float64 {
mat := make([][]float64, width) // width
for x := range mat {
mat[x] = make([]float64, height)
}
return mat
}
// mapRange map range to another range
func mapRange(v, v1, v2, min, max float64) float64 {
return min + ((max-min)/(v2-v1))*(v-v1)
}
func imageToSlice(img image.Image) [][]float64 {
// Convert image.Image to image.Gray
grayImg := image.NewGray(img.Bounds())
draw.Draw(grayImg, grayImg.Bounds(), img, image.Point{}, draw.Src)
width := grayImg.Bounds().Size().X
height := grayImg.Bounds().Size().Y
matrix := make2DMatrix(width, height)
for x := 0; x < width; x++ {
for y := 0; y < height; y++ {
grayValue := float64(grayImg.GrayAt(x, y).Y)
matrix[x][y] = mapRange(grayValue, 0, 255, -1, 1)
}
}
return matrix
}
func sliceToImage(m [][]float64) *image.Gray {
width := len(m)
height := len(m[0])
grayImg := image.NewGray(image.Rect(0, 0, width, height))
for x := 0; x < width; x++ {
for y := 0; y < height; y++ {
v := m[x][y]
grayValue := color.Gray{uint8(mapRange(v, -1, 1, 0, 255))}
grayImg.SetGray(x, y, grayValue)
}
}
return grayImg
}
func openImage(filename string) image.Image {
f, err := os.Open(filename)
if err != nil {
log.Fatalf("os.Open failed: %v", err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
log.Fatalf("image.Decode failed: %v", err)
}
return img
}
func saveImage(filename string, img image.Image) {
f, err := os.Create(filename)
if err != nil {
log.Fatalf("os.Create failed: %v", err)
}
defer f.Close()
err = png.Encode(f, img)
if err != nil {
log.Fatalf("png.Encode failed: %v", err)
}
}