-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathahash.go
64 lines (50 loc) · 1.18 KB
/
ahash.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
package imgsim
import (
"image"
"github.com/nfnt/resize"
)
// AverageHash calculates the average hash of an image. First the image is resized to 8x8.
// Then it is converted to grayscale. Lastly the average hash is computed.
func AverageHash(img image.Image) Hash {
img = resize.Resize(8, 8, img, resize.NearestNeighbor)
img = rgbaToGray(img)
mean := mean(img)
return calcAvgHash(img, mean)
}
// mean computes the mean of all pixels.
func mean(img image.Image) uint32 {
rect := img.Bounds()
w := rect.Max.X - rect.Min.X
h := rect.Max.Y - rect.Min.Y
t := uint32(w * h)
if t == 0 {
return 0
}
var x, y int
var r, sum uint32
for x = rect.Min.X; x < rect.Max.X; x++ {
for y = rect.Min.Y; y < rect.Max.Y; y++ {
r, _, _, _ = img.At(x, y).RGBA()
sum += r
}
}
return sum / t
}
// calcAvgHash computes the average hash for the given image and mean.
func calcAvgHash(img image.Image, mean uint32) Hash {
var x, y int
var hash, p Hash
p = 1
var r uint32
rect := img.Bounds()
for y = rect.Min.Y; y < rect.Max.Y; y++ {
for x = rect.Min.X; x < rect.Max.X; x++ {
r, _, _, _ = img.At(x, y).RGBA()
if r > mean {
hash |= p
}
p = p << 1
}
}
return hash
}