forked from insionng/sdc
/
gopha.go
75 lines (64 loc) · 1.48 KB
/
gopha.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
package helper
import (
"bytes"
"image"
//"github.com/nfnt/resize"
)
func PHA(m image.Image) string {
// Step 1: resize picture to 8*8.
//m = resize.Resize(8, 8, m, resize.NearestNeighbor)
m = Resize(m, m.Bounds(), 8, 8)
// Step 2: grayscale picture.
gray := grayscaleImg(m)
// Step 3: calculate average value.
avg := calAvgValue(gray)
// Step 4: get fingerprint.
fg := getFingerprint(avg, gray)
return string(fg)
}
// grayscaleImg converts picture to grayscale.
func grayscaleImg(src image.Image) []byte {
// Create a new grayscale image
bounds := src.Bounds()
w, h := bounds.Max.X, bounds.Max.Y
gray := make([]byte, w*h)
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
r, g, b, _ := src.At(x, y).RGBA()
gray[x+y*8] = byte((r*30 + g*59 + b*11) / 100)
}
}
return gray
}
// calAvgValue returns average value of color of picture.
func calAvgValue(gray []byte) byte {
sum := 0
for _, v := range gray {
sum += int(v)
}
return byte(sum / len(gray))
}
// getFingerprint returns fingerprint of a picture.
func getFingerprint(avg byte, gray []byte) string {
var buf bytes.Buffer
for _, v := range gray {
if avg >= v {
buf.WriteByte('1')
} else {
buf.WriteByte('0')
}
}
return buf.String()
}
// Pha Compare
func CompareDiff(fg1, fg2 string) int {
diff := 0
fbyte := []byte(fg1)
fbyte2 := []byte(fg2)
for i, v := range fbyte {
if fbyte2[i] != v {
diff++
}
}
return diff
}