goimagehash/imagehash.go

66 lines
1.4 KiB
Go
Raw Normal View History

2017-07-28 10:18:24 -07:00
// Copyright 2017 The goimagehash Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package goimagehash
import (
"errors"
)
// hashKind describes the kinds of hash.
type hashKind int
2017-07-31 07:24:04 -07:00
// ImageHash is a struct of hash computation.
2017-07-28 10:18:24 -07:00
type ImageHash struct {
hash uint64
kind hashKind
}
const (
2017-07-31 07:24:04 -07:00
Unknown hashKind = iota // Unknown Hash
AHash // Average Hash
PHash // Perceptual Hash
DHash // Difference Hash
2017-08-03 06:35:50 -07:00
WHash // Wavelet Hash
2017-07-28 10:18:24 -07:00
)
2017-07-31 07:24:04 -07:00
// NewImageHash function creates a new image hash.
2017-07-28 10:18:24 -07:00
func NewImageHash(hash uint64, kind hashKind) *ImageHash {
return &ImageHash{hash: hash, kind: kind}
}
2017-07-31 07:24:04 -07:00
// Distance method returns a distance between two hashes.
2017-07-28 10:18:24 -07:00
func (h *ImageHash) Distance(other *ImageHash) (int, error) {
if h.GetKind() != other.GetKind() {
return -1, errors.New("Image hashes's kind should be identical.")
}
diff := 0
lhash := h.GetHash()
rhash := other.GetHash()
hamming := lhash ^ rhash
for hamming != 0 {
diff += int(hamming & 1)
hamming >>= 1
}
return diff, nil
}
2017-07-31 07:24:04 -07:00
// GetHash method returns a 64bits hash value.
2017-07-28 10:18:24 -07:00
func (h *ImageHash) GetHash() uint64 {
return h.hash
}
2017-07-31 07:24:04 -07:00
// GetKind method returns a kind of image hash.
2017-07-28 10:18:24 -07:00
func (h *ImageHash) GetKind() hashKind {
return h.kind
}
2017-07-31 07:24:04 -07:00
// Set method sets a bit of index.
2017-07-28 10:18:24 -07:00
func (h *ImageHash) Set(idx int) {
h.hash |= 1 << uint(idx)
}