This repository has been archived by the owner on Mar 24, 2018. It is now read-only.
/
image.go
83 lines (71 loc) · 1.82 KB
/
image.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
package util
import (
"image"
"image/color"
"image/png"
"math"
"os"
"path"
)
/**
* GetMatch returns the percentage (0.0 .. 1.0) of how much the passed image
* equals to the one referenced via file name.
*/
func GetMatch(refName string, input image.Image) float32 {
refFile, _ := os.Open(refName)
refImg, _ := png.Decode(refFile)
refFile.Close()
dx := refImg.Bounds().Dx()
dy := refImg.Bounds().Dy()
equal := 0
for y := 0; y < dy; y++ {
for x := 0; x < dx; x++ {
if DoesPixelMatch(refImg.At(x, y), x, y, input, 5) {
equal++
}
}
}
return float32(equal) / float32(dx*dy)
}
func DoesPixelMatch(pixel color.Color, x, y int, ref image.Image, delta int) bool {
result := DoesColorMatch(pixel, ref.At(x, y), delta)
if !result {
rows := make([]int, 0, 2)
columns := make([]int, 0, 2)
if y > 0 {
rows = append(rows, y-1)
}
if (y + 1) < ref.Bounds().Dy() {
rows = append(rows, y+1)
}
if x > 0 {
columns = append(columns, x-1)
}
if (x + 1) < ref.Bounds().Dx() {
columns = append(columns, x+1)
}
for rowIndex := 0; !result && rowIndex < len(rows); rowIndex++ {
for columnIndex := 0; !result && columnIndex < len(columns); columnIndex++ {
result = DoesColorMatch(pixel, ref.At(columns[columnIndex], rows[rowIndex]), delta)
}
}
}
return result
}
func DoesColorMatch(p1 color.Color, p2 color.Color, delta int) bool {
r1, g1, b1, a1 := p1.RGBA()
r2, g2, b2, a2 := p2.RGBA()
return math.Abs(float64(r1-r2)) <= float64(delta) &&
math.Abs(float64(g1-g2)) <= float64(delta) &&
math.Abs(float64(b1-b2)) <= float64(delta) &&
math.Abs(float64(a1-a2)) <= float64(delta)
}
func SaveImage(name string, img image.Image) {
os.MkdirAll(path.Dir(name), os.FileMode(0755))
writer, err := os.Create(name)
if err != nil {
panic(err)
}
defer writer.Close()
png.Encode(writer, img)
}