imghash

package module
v2.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 13 Imported by: 0

README

imghash logo

Go implementation of multiple perceptual hash algorithms for images.

CI status Coverage status Go reference Go report card MIT license

Documentation

Detailed documentation has moved to the Wiki:

Installing

go get -u github.com/ajdnik/imghash/v2
import "github.com/ajdnik/imghash/v2"

Most consumers only need the top-level imghash package. Core types (Hash, Binary, UInt8, Float64, Distance) are re-exported there.

Quick Start

If you're unsure which hash to pick, start with PDQ.

package main

import (
  "fmt"

  "github.com/ajdnik/imghash/v2"
)

func main() {
  pdq, err := imghash.NewPDQ()
  if err != nil {
    panic(err)
  }

  h1, err := imghash.HashFile(pdq, "image1.png")
  if err != nil {
    panic(err)
  }

  h2, err := imghash.HashFile(pdq, "image2.png")
  if err != nil {
    panic(err)
  }

  dist, err := pdq.Compare(h1, h2)
  if err != nil {
    panic(err)
  }

  fmt.Printf("Distance: %v\n", dist)
}

Algorithms at a Glance

Algorithm Hash type Default metric
Average Binary Hamming
Difference Binary Hamming
Median Binary Hamming
PHash Binary Weighted Hamming
WHash Binary Hamming
MarrHildreth Binary Hamming
BlockMean Binary Hamming
PDQ Binary Hamming
RASH Binary Hamming
ColorMoment Float64 L2 (Euclidean)
Zernike Float64 L2 (Euclidean)
GIST Float64 Cosine
BoVW (Histogram) Float64 Cosine
BoVW (MinHash) Float64 Jaccard
BoVW (SimHash) Binary Jaccard
CLD UInt8 L2 (Euclidean)
EHD UInt8 L1 (Manhattan)
LBP UInt8 Chi-Square
HOGHash UInt8 Cosine
RadialVariance UInt8 L1 (Manhattan)

See Algorithms for options, defaults, references, and examples.

Community

License

Imghash is released under the MIT license. See LICENSE.

Documentation

Overview

Package imghash provides perceptual image hashing algorithms and similarity metrics for comparing images by visual content.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidSize is returned when width or height is zero.
	ErrInvalidSize = errors.New("imghash: size dimensions must be greater than zero")
	// ErrInvalidInterpolation is returned when an unsupported interpolation enum is supplied.
	ErrInvalidInterpolation = errors.New("imghash: invalid interpolation method")
	// ErrInvalidBlockSize is returned when block width or height is zero.
	ErrInvalidBlockSize = errors.New("imghash: block size dimensions must be greater than zero")
	// ErrInvalidAngles is returned when the number of projection angles is not positive.
	ErrInvalidAngles = errors.New("imghash: angles must be greater than zero")
	// ErrInvalidKernelSize is returned when the Gaussian kernel size is not positive.
	ErrInvalidKernelSize = errors.New("imghash: kernel size must be greater than zero")
	// ErrInvalidScale is returned when the scale parameter is not positive.
	ErrInvalidScale = errors.New("imghash: scale must be greater than zero")
	// ErrInvalidAlpha is returned when the alpha parameter is not positive.
	ErrInvalidAlpha = errors.New("imghash: alpha must be greater than zero")
	// ErrInvalidSigma is returned when sigma is negative.
	ErrInvalidSigma = errors.New("imghash: sigma must not be negative")
	// ErrInvalidLevel is returned when the wavelet decomposition level is not positive.
	ErrInvalidLevel = errors.New("imghash: level must be greater than zero")
	// ErrInvalidGridSize is returned when grid width or height is zero.
	ErrInvalidGridSize = errors.New("imghash: grid size dimensions must be greater than zero")
	// ErrInvalidCellSize is returned when the cell size is zero.
	ErrInvalidCellSize = errors.New("imghash: cell size must be greater than zero")
	// ErrInvalidNumBins is returned when the number of histogram bins is zero.
	ErrInvalidNumBins = errors.New("imghash: number of bins must be greater than zero")
	// ErrInvalidRings is returned when the number of concentric rings is not positive.
	ErrInvalidRings = errors.New("imghash: rings must be greater than zero")
	// ErrInvalidDegree is returned when the maximum Zernike degree is not positive.
	ErrInvalidDegree = errors.New("imghash: degree must be greater than zero")
	// ErrInvalidBoVWFeatureType is returned when an unknown BoVW feature extractor enum is supplied.
	ErrInvalidBoVWFeatureType = errors.New("imghash: invalid BoVW feature type")
	// ErrInvalidBoVWStorageType is returned when an unknown BoVW storage enum is supplied.
	ErrInvalidBoVWStorageType = errors.New("imghash: invalid BoVW storage type")
	// ErrInvalidVocabularySize is returned when BoVW vocabulary size is zero.
	ErrInvalidVocabularySize = errors.New("imghash: vocabulary size must be greater than zero")
	// ErrInvalidKeypoints is returned when the maximum keypoint count is zero.
	ErrInvalidKeypoints = errors.New("imghash: max keypoints must be greater than zero")
	// ErrInvalidSignatureSize is returned when MinHash or SimHash size is zero.
	ErrInvalidSignatureSize = errors.New("imghash: signature size must be greater than zero")
)

Constructor validation errors.

View Source
var ErrHashLengthMismatch = errors.New("imghash: hash lengths must match")

ErrHashLengthMismatch is reported when two hashes of the expected type have different lengths and cannot be compared safely.

View Source
var ErrIncompatibleHash = hashtype.ErrIncompatibleHash

ErrIncompatibleHash is reported when a binary-only metric (Hamming or weighted Hamming) is used with incompatible hash types.

Functions

func Compare

func Compare(h1, h2 hashtype.Hash, fn ...DistanceFunc) (similarity.Distance, error)

Compare computes the distance between two hashes. By default it uses the natural metric for their type: Hamming distance for Binary hashes, L2 (Euclidean) distance for UInt8 and Float64 hashes. Pass an optional DistanceFunc to override the metric, e.g.:

Compare(h1, h2, similarity.Cosine)
Example
avg, err := imghash.NewAverage()
if err != nil {
	panic(err)
}
h1, err := imghash.HashFile(avg, "assets/lena.jpg")
if err != nil {
	panic(err)
}
h2, err := imghash.HashFile(avg, "assets/cat.jpg")
if err != nil {
	panic(err)
}

dist, err := imghash.Compare(h1, h2)
if err != nil {
	panic(err)
}
fmt.Println(dist)
Output:

29

func DecodeImage

func DecodeImage(r io.Reader) (image.Image, error)

DecodeImage decodes an image from the given reader. It supports JPEG, PNG, and GIF formats.

func HashFile

func HashFile(hasher Hasher, path string) (hashtype.Hash, error)

HashFile is a convenience that opens an image file and computes its hash.

Example
avg, err := imghash.NewAverage()
if err != nil {
	panic(err)
}
hash, err := imghash.HashFile(avg, "assets/cat.jpg")
if err != nil {
	panic(err)
}
fmt.Println(hash)
Output:

[255 255 15 7 1 0 0 0]

func HashReader

func HashReader(hasher Hasher, r io.Reader) (hashtype.Hash, error)

HashReader is a convenience that decodes an image from a reader and computes its hash.

Example
f, err := os.Open("assets/cat.jpg")
if err != nil {
	panic(err)
}
defer func() { _ = f.Close() }()

avg, err := imghash.NewAverage()
if err != nil {
	panic(err)
}
hash, err := imghash.HashReader(avg, f)
if err != nil {
	panic(err)
}
fmt.Println(hash)
Output:

[255 255 15 7 1 0 0 0]

func OpenImage

func OpenImage(path string) (image.Image, error)

OpenImage reads and decodes an image from the given file path. It supports JPEG, PNG, and GIF formats.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
fmt.Println(img.Bounds())
Output:

(0,0)-(490,733)

Types

type AlphaOption

type AlphaOption interface {
	MarrHildrethOption
}

AlphaOption sets the alpha parameter.

func WithAlpha

func WithAlpha(alpha float64) AlphaOption

WithAlpha sets the alpha parameter. Applies to MarrHildreth.

type AnglesOption

type AnglesOption interface {
	RadialVarianceOption
}

AnglesOption sets the number of projection angles.

func WithAngles

func WithAngles(angles int) AnglesOption

WithAngles sets the number of projection angles. Applies to RadialVariance.

type Average

type Average struct {
	// contains filtered or unexported fields
}

Average is a perceptual hash that uses the method described in Looks Like It by Dr. Neal Krawetz.

See https://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html for more information.

func NewAverage

func NewAverage(opts ...AverageOption) (Average, error)

NewAverage creates a new Average hash with the given options. Without options, sensible defaults are used.

func (Average) Calculate

func (ah Average) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
// Read image from file
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
// Create new Average Hash using default parameters
avg, err := imghash.NewAverage()
if err != nil {
	panic(err)
}
// Calculate hash
hash, err := avg.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[255 255 15 7 1 0 0 0]

func (Average) Compare

func (ah Average) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the Hamming distance between two Average hashes.

type AverageOption

type AverageOption interface {
	// contains filtered or unexported methods
}

AverageOption configures the Average hash algorithm.

type Binary

type Binary = hashtype.Binary

Binary represents a hash where the smallest element is a bit.

type BlockMean

type BlockMean struct {
	// contains filtered or unexported fields
}

BlockMean is a perceptual hash that uses the method described in Block Mean Value Based Image Perceptual Hashing; Yang et. al.

See https://ieeexplore.ieee.org/document/4041692 for more information.

func NewBlockMean

func NewBlockMean(opts ...BlockMeanOption) (BlockMean, error)

NewBlockMean creates a new BlockMean hash with the given options. Without options, sensible defaults are used.

func (BlockMean) Calculate

func (bh BlockMean) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
// Read image from file
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
// Create new Block Mean Hash using default parameters
block, err := imghash.NewBlockMean()
if err != nil {
	panic(err)
}
// Calculate hash
hash, err := block.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[255 255 255 255 255 255 255 255 255 225 127 0 63 0 15 0 7 2 3 0 1 0 1 0 0 0 0 0 0 0 116 4]

func (BlockMean) Compare

func (bh BlockMean) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the Hamming distance between two BlockMean hashes.

type BlockMeanMethod

type BlockMeanMethod int

BlockMeanMethod represents the method used when computing the mean of blocks.

const (
	// Direct method constructs blocks with no overlap or rotation.
	Direct BlockMeanMethod = iota
	// Overlap method constructs blocks by overlapping them, the degree of overlap is set to be half of a block.
	Overlap
	// Rotation method uses the same approach as Direct but also hashes 24 rotated
	// image variants in 15-degree steps.
	Rotation
	// RotationOverlap uses the same approach as Overlap but also hashes 24 rotated
	// image variants in 15-degree steps.
	RotationOverlap
)

type BlockMeanMethodOption

type BlockMeanMethodOption interface {
	BlockMeanOption
}

BlockMeanMethodOption sets the block construction method.

func WithBlockMeanMethod

func WithBlockMeanMethod(method BlockMeanMethod) BlockMeanMethodOption

WithBlockMeanMethod sets the block construction method. Applies to BlockMean.

type BlockMeanOption

type BlockMeanOption interface {
	// contains filtered or unexported methods
}

BlockMeanOption configures the BlockMean hash algorithm.

type BlockSizeOption

type BlockSizeOption interface {
	BlockMeanOption
}

BlockSizeOption sets block dimensions for BlockMean.

func WithBlockSize

func WithBlockSize(width, height uint) BlockSizeOption

WithBlockSize sets the block dimensions for block mean hashing. Applies to BlockMean.

type BoVW added in v2.3.0

type BoVW struct {
	// contains filtered or unexported fields
}

BoVW implements bag-of-visual-words hashing using ORB-like or AKAZE-like local descriptors. The resulting representation can be a normalized histogram, MinHash signature, or SimHash bit-signature.

func NewBoVW added in v2.3.0

func NewBoVW(opts ...BoVWOption) (BoVW, error)

NewBoVW creates a new BoVW hasher with the given options. Without options, sensible defaults are used.

func (BoVW) Calculate added in v2.3.0

func (b BoVW) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a BoVW representation hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
bovw, err := imghash.NewBoVW(
	imghash.WithBoVWFeature(imghash.BoVWAKAZE),
	imghash.WithBoVWStorage(imghash.BoVWMinHash),
	imghash.WithMinHashSize(32),
)
if err != nil {
	panic(err)
}
hash, err := bovw.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash.Len())
Output:

32

func (BoVW) Compare added in v2.3.0

func (b BoVW) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes distance using cosine for histogram storage and Jaccard for MinHash/SimHash storage.

type BoVWFeatureOption added in v2.3.0

type BoVWFeatureOption interface {
	BoVWOption
}

BoVWFeatureOption sets the local feature extractor for BoVW.

func WithBoVWFeature added in v2.3.0

func WithBoVWFeature(feature BoVWFeatureType) BoVWFeatureOption

WithBoVWFeature sets the local feature extractor used by BoVW. Applies to BoVW.

type BoVWFeatureType added in v2.3.0

type BoVWFeatureType uint8

BoVWFeatureType selects the local feature extractor used by BoVW.

const (
	// BoVWORB uses an ORB-like FAST + BRIEF pipeline.
	BoVWORB BoVWFeatureType = iota + 1
	// BoVWAKAZE uses an AKAZE-like Hessian detector with binary descriptors.
	BoVWAKAZE
)

type BoVWOption added in v2.3.0

type BoVWOption interface {
	// contains filtered or unexported methods
}

BoVWOption configures the BoVW hash algorithm.

type BoVWStorageOption added in v2.3.0

type BoVWStorageOption interface {
	BoVWOption
}

BoVWStorageOption sets the output storage type for BoVW.

func WithBoVWStorage added in v2.3.0

func WithBoVWStorage(storage BoVWStorageType) BoVWStorageOption

WithBoVWStorage sets the BoVW output storage representation. Applies to BoVW.

type BoVWStorageType added in v2.3.0

type BoVWStorageType uint8

BoVWStorageType selects the global BoVW representation format.

const (
	// BoVWHistogram stores a normalized visual-word histogram.
	BoVWHistogram BoVWStorageType = iota + 1
	// BoVWMinHash stores a MinHash signature over visual words.
	BoVWMinHash
	// BoVWSimHash stores a SimHash bit-signature over visual words.
	BoVWSimHash
)

type CLD added in v2.3.0

type CLD struct {
	// contains filtered or unexported fields
}

CLD is an MPEG-7 Color Layout Descriptor style perceptual hash. The image is converted to YCbCr, summarised into an 8x8 layout, transformed with a 2-D DCT per channel, then low-frequency zig-zag coefficients are quantised into a compact 12-element descriptor.

func NewCLD added in v2.3.0

func NewCLD(opts ...CLDOption) (CLD, error)

NewCLD creates a new CLD hash with the given options. Without options, sensible defaults are used.

func (CLD) Calculate added in v2.3.0

func (c CLD) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns an MPEG-7 CLD style perceptual hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
cld, err := imghash.NewCLD()
if err != nil {
	panic(err)
}
hash, err := cld.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[36 26 31 27 19 16 28 15 17 35 16 13]

func (CLD) Compare added in v2.3.0

func (c CLD) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the L2 (Euclidean) distance between two CLD hashes.

type CLDOption added in v2.3.0

type CLDOption interface {
	// contains filtered or unexported methods
}

CLDOption configures the CLD hash algorithm.

type CellSizeOption

type CellSizeOption interface {
	HOGHashOption
}

CellSizeOption sets the cell size in pixels for HOG computation.

func WithCellSize

func WithCellSize(size uint) CellSizeOption

WithCellSize sets the cell size in pixels (square cells) for HOG computation. Applies to HOGHash.

type ColorMoment

type ColorMoment struct {
	// contains filtered or unexported fields
}

ColorMoment is a perceptual hash that uses the method described in Perceptual Hashing for Color Images Using Invariant Moments; Tang et. al.

See https://www.researchgate.net/publication/286870507_Perceptual_hashing_for_color_images_using_invariant_moments for more information.

func NewColorMoment

func NewColorMoment(opts ...ColorMomentOption) (ColorMoment, error)

NewColorMoment creates a new ColorMoment hash with the given options. Without options, sensible defaults are used.

func (ColorMoment) Calculate

func (ch ColorMoment) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
// Read image from file
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
// Create new Color Moment Hash using default parameters
color, err := imghash.NewColorMoment()
if err != nil {
	panic(err)
}
// Calculate hash
hash, err := color.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)

func (ColorMoment) Compare

func (ch ColorMoment) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the L2 (Euclidean) distance between two ColorMoment hashes.

type ColorMomentOption

type ColorMomentOption interface {
	// contains filtered or unexported methods
}

ColorMomentOption configures the ColorMoment hash algorithm.

type Comparer

type Comparer interface {
	Compare(hashtype.Hash, hashtype.Hash) (similarity.Distance, error)
}

Comparer measures the similarity between two hashes using a distance metric appropriate for the algorithm that produced them. It is implemented by all hash algorithms in this package.

type DegreeOption added in v2.3.0

type DegreeOption interface {
	ZernikeOption
}

DegreeOption sets the maximum Zernike degree.

func WithDegree added in v2.3.0

func WithDegree(degree int) DegreeOption

WithDegree sets the maximum Zernike degree. Applies to Zernike.

type Difference

type Difference struct {
	// contains filtered or unexported fields
}

Difference is a perceptual hash that uses the method described in Kind of Like That by Dr. Neal Krawetz.

See https://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html for more information.

func NewDifference

func NewDifference(opts ...DifferenceOption) (Difference, error)

NewDifference creates a new Difference hash with the given options. Without options, sensible defaults are used.

func (Difference) Calculate

func (dh Difference) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
// Read image from file
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
// Create new Difference Hash using default parameters
diff, err := imghash.NewDifference()
if err != nil {
	panic(err)
}
// Calculate hash
hash, err := diff.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[6 2 194 64 92 60 16 16]

func (Difference) Compare

func (dh Difference) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the Hamming distance between two Difference hashes.

type DifferenceOption

type DifferenceOption interface {
	// contains filtered or unexported methods
}

DifferenceOption configures the Difference hash algorithm.

type Distance

type Distance = similarity.Distance

Distance represents a similarity measure between two hashes.

type DistanceFunc

type DistanceFunc func(hashtype.Hash, hashtype.Hash) (similarity.Distance, error)

DistanceFunc computes a distance between two hashes. All functions in the similarity package (Hamming, L1, L2, Cosine, ChiSquare, PCC, Jaccard) satisfy this signature and can be passed directly to WithDistance.

type DistanceOption

DistanceOption overrides the comparison function used by Compare.

func WithDistance

func WithDistance(fn DistanceFunc) DistanceOption

WithDistance overrides the default distance function used by Compare. All functions in the similarity package (Hamming, L1, L2, Cosine, ChiSquare, PCC, Jaccard) satisfy DistanceFunc and can be passed directly. Applies to all algorithms.

type EHD added in v2.3.0

type EHD struct {
	// contains filtered or unexported fields
}

EHD is an MPEG-7 Edge Histogram Descriptor style perceptual hash. The image is resized, converted to grayscale, split into a 4x4 grid, and each cell is described by a 5-bin histogram of local edge orientations. Each histogram bin is quantised to 3 bits, producing an 80-element hash.

func NewEHD added in v2.3.0

func NewEHD(opts ...EHDOption) (EHD, error)

NewEHD creates a new EHD hash with the given options. Without options, sensible defaults are used.

func (EHD) Calculate added in v2.3.0

func (e EHD) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns an MPEG-7 EHD style perceptual hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
ehd, err := imghash.NewEHD()
if err != nil {
	panic(err)
}
hash, err := ehd.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[0 2 1 3 0 1 1 1 4 0 2 2 4 4 0 2 5 4 6 1 1 4 4 6 2 2 4 6 6 4 2 4 6 6 4 4 4 5 6 3 2 5 4 6 5 3 4 6 6 4 2 5 6 6 4 1 6 6 6 3 1 6 6 5 4 2 5 7 5 4 2 6 7 5 2 2 6 6 6 2]

func (EHD) Compare added in v2.3.0

func (e EHD) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the L1 (Manhattan) distance between two EHD hashes.

type EHDOption added in v2.3.0

type EHDOption interface {
	// contains filtered or unexported methods
}

EHDOption configures the EHD hash algorithm.

type Float64

type Float64 = hashtype.Float64

Float64 represents a hash where the smallest element is a float64.

type GIST added in v2.3.0

type GIST struct {
	// contains filtered or unexported fields
}

GIST is a holistic scene descriptor based on a bank of oriented Gabor filters pooled over a coarse spatial grid.

Based on: A. Oliva and A. Torralba, "Modeling the Shape of the Scene: A Holistic Representation of the Spatial Envelope" (2001).

func NewGIST added in v2.3.0

func NewGIST(opts ...GISTOption) (GIST, error)

NewGIST creates a new GIST hash with the given options. Without options, sensible defaults are used.

func (GIST) Calculate added in v2.3.0

func (g GIST) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
g, err := imghash.NewGIST()
if err != nil {
	panic(err)
}
hash, err := g.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash.Len())
Output:

320

func (GIST) Compare added in v2.3.0

func (g GIST) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the cosine distance between two GIST hashes.

type GISTOption added in v2.3.0

type GISTOption interface {
	// contains filtered or unexported methods
}

GISTOption configures the GIST hash algorithm.

type GridSizeOption

type GridSizeOption interface {
	LBPOption
	GISTOption
}

GridSizeOption sets the grid cell count for spatial histograms.

func WithGridSize

func WithGridSize(x, y uint) GridSizeOption

WithGridSize sets the number of grid cells used to divide the image for spatial histogram computation. Applies to LBP and GIST.

type HOGHash

type HOGHash struct {
	// contains filtered or unexported fields
}

HOGHash is a perceptual hash based on Histogram of Oriented Gradients. It computes gradient magnitudes and orientations at each pixel, divides the image into cells, builds an orientation histogram per cell weighted by gradient magnitude, and concatenates them into a single hash vector.

Based on Histograms of Oriented Gradients for Human Detection; Dalal and Triggs.

See https://ieeexplore.ieee.org/document/1467360 for more information.

func NewHOGHash

func NewHOGHash(opts ...HOGHashOption) (HOGHash, error)

NewHOGHash creates a new HOGHash with the given options. Without options, sensible defaults are used.

func (HOGHash) Calculate

func (hh HOGHash) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
hog, err := imghash.NewHOGHash(imghash.WithSize(32, 32))
if err != nil {
	panic(err)
}
hash, err := hog.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[42 41 55 40 188 216 236 255 65 255 47 80 5 111 116 123 105 66 98 47 254 131 82 86 100 45 47 214 151 131 255 205 154 196 227 67 84 216 255 221 186 170 73 89 57 51 60 161 255 71 30 63 0 71 43 46 150 193 255 29 122 53 56 58 48 125 112 255 115 77 100 133 150 255 169 107 84 60 87 50 107 89 199 255 95 77 29 36 43 57 2 9 121 116 226 255 201 68 31 33 133 172 255 87 34 131 62 12 59 60 68 92 198 254 212 30 30 25 18 60 100 254 78 57 29 0 94 35 191 143 255 128 36 78 63 44 71 99 255 118 63 3 69 35]

func (HOGHash) Compare

func (hh HOGHash) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the cosine distance between two HOGHash hashes.

type HOGHashOption

type HOGHashOption interface {
	// contains filtered or unexported methods
}

HOGHashOption configures the HOGHash algorithm.

type Hash

type Hash = hashtype.Hash

Hash is the common interface for all hash representations.

type Hasher

type Hasher interface {
	Calculate(image.Image) (hashtype.Hash, error)
}

Hasher computes a perceptual hash from an image. It is implemented by all hash algorithms in this package: Average, Difference, PHash, Median, BlockMean, MarrHildreth, RadialVariance, ColorMoment, CLD, EHD, WHash, LBP, HOGHash, BoVW, PDQ, RASH, Zernike, and GIST.

type HasherComparer

type HasherComparer interface {
	Hasher
	Comparer
}

HasherComparer combines Hasher and Comparer into a single interface for algorithms that can both compute and compare hashes.

type Interpolation

type Interpolation int

Interpolation specifies the resize interpolation method used during hash computation.

func (Interpolation) String

func (i Interpolation) String() string

String returns the name of the interpolation method.

Example
fmt.Println(imghash.Bilinear)
fmt.Println(imghash.Bicubic)
fmt.Println(imghash.Lanczos3)
Output:

Bilinear
Bicubic
Lanczos3

type InterpolationOption

InterpolationOption sets the resize interpolation method.

func WithInterpolation

func WithInterpolation(interp Interpolation) InterpolationOption

WithInterpolation sets the resize interpolation method. Applies to Average, Difference, Median, PHash, BlockMean, MarrHildreth, ColorMoment, CLD, EHD, WHash, LBP, HOGHash, BoVW, PDQ, RASH, Zernike, and GIST.

type KernelSizeOption

type KernelSizeOption interface {
	MarrHildrethOption
	ColorMomentOption
}

KernelSizeOption sets the Gaussian kernel size.

func WithKernelSize

func WithKernelSize(size int) KernelSizeOption

WithKernelSize sets the Gaussian kernel size. Applies to MarrHildreth and ColorMoment.

type LBP

type LBP struct {
	// contains filtered or unexported fields
}

LBP is a perceptual hash based on Local Binary Patterns. It computes a basic 3×3 LBP code for each pixel, divides the image into a grid of cells, builds a 256-bin histogram per cell, and concatenates them into a single hash vector.

Based on Multiresolution Gray-Scale and Rotation Invariant Texture Classification with Local Binary Patterns; Ojala et. al.

See https://ieeexplore.ieee.org/document/1017623 for more information.

func NewLBP

func NewLBP(opts ...LBPOption) (LBP, error)

NewLBP creates a new LBP hash with the given options. Without options, sensible defaults are used.

func (LBP) Calculate

func (lh LBP) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
lbp, err := imghash.NewLBP()
if err != nil {
	panic(err)
}
hash, err := lbp.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[140 97 12 39 15 6 22 68 13 10 1 2 24 14 62 193 107 18 7 6 6 0 9 7 42 5 2 2 73 7 186 105 14 8 1 3 1 0 1 4 1 0 0 0 1 0 3 16 53 7 3 3 3 0 4 3 41 2 2 1 85 2 85 41 16 6 1 2 2 0 1 3 1 0 0 0 1 0 2 2 6 1 0 0 0 0 0 0 2 0 0 0 3 0 3 2 28 11 2 5 2 0 3 4 2 1 0 0 3 0 5 8 87 8 4 3 2 0 4 3 70 3 3 2 59 3 61 30 18 44 0 35 1 3 1 66 3 4 0 2 2 6 5 73 11 6 0 3 0 0 1 2 4 3 0 1 5 3 9 31 1 2 0 2 0 0 0 3 0 0 0 0 0 0 0 5 3 3 0 2 0 0 0 1 2 1 0 2 4 2 5 19 30 82 1 85 1 2 3 55 3 5 0 3 3 5 4 46 17 6 1 3 0 0 1 3 8 3 0 2 4 3 7 23 74 198 4 94 2 3 5 58 5 9 0 5 6 7 12 103 255 121 15 45 3 3 11 30 99 36 7 22 60 23 114 217]

func (LBP) Compare

func (lh LBP) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the chi-square distance between two LBP hashes.

type LBPOption

type LBPOption interface {
	// contains filtered or unexported methods
}

LBPOption configures the LBP hash algorithm.

type LevelOption

type LevelOption interface {
	WHashOption
}

LevelOption sets the wavelet decomposition level.

func WithLevel

func WithLevel(level int) LevelOption

WithLevel sets the number of Haar wavelet decomposition levels. Applies to WHash.

type MarrHildreth

type MarrHildreth struct {
	// contains filtered or unexported fields
}

MarrHildreth is a perceptual hash that uses the method described in Implementation and Benchmarking of Perceptual Image Hash Functions; Zauner et. al.

See https://www.researchgate.net/publication/252340846_Rihamark_Perceptual_image_hash_benchmarking for more information.

Example (Calculate)
// Read image from file
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
// Create new Marr-Hildreth Hash using default parameters
marr, err := imghash.NewMarrHildreth()
if err != nil {
	panic(err)
}
// Calculate hash
hash, err := marr.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[92 190 42 111 87 107 101 164 184 24 75 41 185 54 178 162 26 236 155 150 108 98 233 112 56 235 124 177 139 159 148 66 89 38 229 47 195 36 158 180 85 115 79 165 92 131 225 252 54 148 218 61 99 92 82 141 141 96 112 186 153 208 174 112 252 150 153 172 173 206 43 130]

func NewMarrHildreth

func NewMarrHildreth(opts ...MarrHildrethOption) (MarrHildreth, error)

NewMarrHildreth creates a new MarrHildreth hash with the given options. Without options, sensible defaults are used.

Example (Options)
mh, err := imghash.NewMarrHildreth(
	imghash.WithScale(1),
	imghash.WithAlpha(2),
	imghash.WithSize(512, 512),
	imghash.WithInterpolation(imghash.Bicubic),
	imghash.WithKernelSize(7),
	imghash.WithSigma(0),
)
if err != nil {
	panic(err)
}
hash, err := imghash.HashFile(mh, "assets/cat.jpg")
if err != nil {
	panic(err)
}
fmt.Println(hash)
Output:

[92 190 42 111 87 107 101 164 184 24 75 41 185 54 178 162 26 236 155 150 108 98 233 112 56 235 124 177 139 159 148 66 89 38 229 47 195 36 158 180 85 115 79 165 92 131 225 252 54 148 218 61 99 92 82 141 141 96 112 186 153 208 174 112 252 150 153 172 173 206 43 130]

func (MarrHildreth) Calculate

func (mhh MarrHildreth) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

func (MarrHildreth) Compare

func (mhh MarrHildreth) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the Hamming distance between two MarrHildreth hashes.

type MarrHildrethOption

type MarrHildrethOption interface {
	// contains filtered or unexported methods
}

MarrHildrethOption configures the MarrHildreth hash algorithm.

type MaxKeypointsOption added in v2.3.0

type MaxKeypointsOption interface {
	BoVWOption
}

MaxKeypointsOption sets the maximum number of BoVW keypoints.

func WithMaxKeypoints added in v2.3.0

func WithMaxKeypoints(count uint) MaxKeypointsOption

WithMaxKeypoints sets the maximum number of BoVW keypoints. Applies to BoVW.

type Median

type Median struct {
	// contains filtered or unexported fields
}

Median is a perceptual hash that uses a similar approach as Average hash. But instead of using mean it uses median to compute the average value. See https://github.com/Quickshot/DupImageLib/blob/3e914588958c4c1871d750de86b30446b9c07a3e/DupImageLib/ImageHashes.cs#L99 for more information.

func NewMedian

func NewMedian(opts ...MedianOption) (Median, error)

NewMedian creates a new Median hash with the given options. Without options, sensible defaults are used.

func (Median) Calculate

func (mh Median) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
// Read image from file
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
// Create new Median Hash using default parameters
med, err := imghash.NewMedian()
if err != nil {
	panic(err)
}
// Calculate hash
hash, err := med.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[255 255 31 7 1 1 1 7]

func (Median) Compare

func (mh Median) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the Hamming distance between two Median hashes.

type MedianOption

type MedianOption interface {
	// contains filtered or unexported methods
}

MedianOption configures the Median hash algorithm.

type MinHashSizeOption added in v2.3.0

type MinHashSizeOption interface {
	BoVWOption
}

MinHashSizeOption sets the MinHash signature size used by BoVW.

func WithMinHashSize added in v2.3.0

func WithMinHashSize(size uint) MinHashSizeOption

WithMinHashSize sets the MinHash signature length used by BoVW. Applies to BoVW.

type NumBinsOption

type NumBinsOption interface {
	HOGHashOption
}

NumBinsOption sets the number of orientation histogram bins.

func WithNumBins

func WithNumBins(bins uint) NumBinsOption

WithNumBins sets the number of orientation histogram bins. Applies to HOGHash.

type PDQ

type PDQ struct {
	// contains filtered or unexported fields
}

PDQ is a perceptual hash that uses the method described in PDQ and TMK+PDQF by Facebook (now Meta). It produces a 256-bit hash robust to JPEG compression, rescaling, and minor edits while remaining fast enough for large-scale deduplication.

See https://github.com/facebook/ThreatExchange/tree/main/pdq for more information.

func NewPDQ

func NewPDQ(opts ...PDQOption) (PDQ, error)

NewPDQ creates a new PDQ hasher with the given options. Without options, sensible defaults are used.

func (PDQ) Calculate

func (p PDQ) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a 256-bit perceptual hash of the image.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
pdq, err := imghash.NewPDQ()
if err != nil {
	panic(err)
}
hash, err := pdq.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[255 0 255 0 233 42 61 168 171 5 179 17 119 2 85 174 152 255 140 217 96 247 72 93 0 253 2 119 4 255 0 255]

func (PDQ) Compare

func (p PDQ) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the Hamming distance between two PDQ hashes.

type PDQOption

type PDQOption interface {
	// contains filtered or unexported methods
}

PDQOption configures the PDQ hash algorithm.

type PHash

type PHash struct {
	// contains filtered or unexported fields
}

PHash is a perceptual hash that uses the method described in Implementation and Benchmarking of Perceptual Image Hash Functions; Zauner et. al.

See https://www.researchgate.net/publication/252340846_Rihamark_Perceptual_image_hash_benchmarking for more information.

func NewPHash

func NewPHash(opts ...PHashOption) (PHash, error)

NewPHash creates a new PHash with the given options. Without options, sensible defaults are used.

func (PHash) Calculate

func (ph PHash) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
// Read image from file
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
// Create new PHash using default parameters
ph, err := imghash.NewPHash()
if err != nil {
	panic(err)
}
// Calculate hash
hash, err := ph.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[170 195 65 29 10 2 34 84]

func (PHash) Compare

func (ph PHash) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the weighted Hamming distance between two PHash hashes using the per-byte weights configured on this hasher.

type PHashOption

type PHashOption interface {
	// contains filtered or unexported methods
}

PHashOption configures the PHash algorithm.

type RASH

type RASH struct {
	// contains filtered or unexported fields
}

RASH is a Rotation Aware Spatial Hash — a perceptual hash designed to be robust against image rotation. It combines concentric ring sampling for rotation invariance, a 1-D DCT for frequency compaction, and median thresholding for binarisation.

Because ring-mean features are inherently rotation-invariant (rotating the image only permutes pixels within a ring, leaving its mean unchanged), the resulting hash stays stable under arbitrary rotations.

Inspired by ring-partition hashing literature:

  • Tang et al., "Robust Image Hashing with Ring Partition and Invariant Vector Distance" (2016)
  • De Roover et al., "Robust image hashing based on radial variance of pixels" (2005)

func NewRASH

func NewRASH(opts ...RASHOption) (RASH, error)

NewRASH creates a new RASH hash with the given options. Without options, sensible defaults are used.

func (RASH) Calculate

func (r RASH) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
rash, err := imghash.NewRASH()
if err != nil {
	panic(err)
}
hash, err := rash.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[46 0 64 32 128 255 255 255]

func (RASH) Compare

func (r RASH) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the Hamming distance between two RASH hashes.

type RASHOption

type RASHOption interface {
	// contains filtered or unexported methods
}

RASHOption configures the RASH hash algorithm.

type RadialVariance

type RadialVariance struct {
	// contains filtered or unexported fields
}

RadialVariance is a perceptual hash that uses the method described in Robust image hashing based on radial variance of pixels; De Roover et. al.

See https://www.researchgate.net/publication/4186555_Robust_image_hashing_based_on_radial_variance_of_pixels for more information.

func NewRadialVariance

func NewRadialVariance(opts ...RadialVarianceOption) (RadialVariance, error)

NewRadialVariance creates a new RadialVariance hash with the given options. Without options, sensible defaults are used.

func (RadialVariance) Calculate

func (rv RadialVariance) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
// Read image from file
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
// Create new Radial Variance Hash using default parameters
rad, err := imghash.NewRadialVariance()
if err != nil {
	panic(err)
}
// Calculate hash
hash, err := rad.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)

func (RadialVariance) Compare

func (rv RadialVariance) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the L1 (Manhattan) distance between two RadialVariance hashes.

type RadialVarianceOption

type RadialVarianceOption interface {
	// contains filtered or unexported methods
}

RadialVarianceOption configures the RadialVariance hash algorithm.

type RingsOption

type RingsOption interface {
	RASHOption
}

RingsOption sets the number of concentric rings.

func WithRings

func WithRings(rings int) RingsOption

WithRings sets the number of concentric rings used for spatial sampling. Applies to RASH.

type ScaleOption

type ScaleOption interface {
	MarrHildrethOption
}

ScaleOption sets the scale parameter.

func WithScale

func WithScale(scale float64) ScaleOption

WithScale sets the scale parameter. Applies to MarrHildreth.

type SigmaOption

SigmaOption sets the Gaussian standard deviation.

func WithSigma

func WithSigma(sigma float64) SigmaOption

WithSigma sets the Gaussian kernel standard deviation. Applies to MarrHildreth, ColorMoment, RadialVariance, and RASH.

type SimHashBitsOption added in v2.3.0

type SimHashBitsOption interface {
	BoVWOption
}

SimHashBitsOption sets the SimHash bit length used by BoVW.

func WithSimHashBits added in v2.3.0

func WithSimHashBits(bits uint) SimHashBitsOption

WithSimHashBits sets the SimHash bit length used by BoVW. Applies to BoVW.

type SizeOption

SizeOption sets width and height for hash computation.

func WithSize

func WithSize(width, height uint) SizeOption

WithSize sets the resize dimensions used during hash computation. Applies to Average, Difference, Median, PHash, BlockMean, MarrHildreth, ColorMoment, CLD, EHD, WHash, LBP, HOGHash, BoVW, RASH, Zernike, and GIST.

type UInt8

type UInt8 = hashtype.UInt8

UInt8 represents a hash where the smallest element is a uint8 value.

type VocabularySizeOption added in v2.3.0

type VocabularySizeOption interface {
	BoVWOption
}

VocabularySizeOption sets the visual vocabulary size used by BoVW.

func WithVocabularySize added in v2.3.0

func WithVocabularySize(size uint) VocabularySizeOption

WithVocabularySize sets the visual vocabulary size used by BoVW. Applies to BoVW.

type WHash

type WHash struct {
	// contains filtered or unexported fields
}

WHash is a perceptual hash based on the Haar wavelet transform. It applies a multi-level 2-D discrete wavelet transform to the image and thresholds the low-frequency (LL) coefficients against their median.

See https://fullstackml.com/wavelet-image-hash-in-python-3504571f3b08 for more information.

func NewWHash

func NewWHash(opts ...WHashOption) (WHash, error)

NewWHash creates a new WHash with the given options. Without options, sensible defaults are used (8×8 hash, 3 levels, Bilinear).

func (WHash) Calculate

func (wh WHash) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
wh, err := imghash.NewWHash()
if err != nil {
	panic(err)
}
hash, err := wh.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)
Output:

[255 255 31 7 3 1 0 47]

func (WHash) Compare

func (wh WHash) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the Hamming distance between two WHash hashes.

type WHashOption

type WHashOption interface {
	// contains filtered or unexported methods
}

WHashOption configures the WHash algorithm.

type WeightsOption

type WeightsOption interface {
	PHashOption
}

WeightsOption sets the per-byte weights for weighted distance.

func WithWeights

func WithWeights(weights []float64) WeightsOption

WithWeights sets the per-byte weights used for weighted Hamming distance. The slice length must match the number of hash bytes (8 for default PHash). Applies to PHash.

type Zernike added in v2.3.0

type Zernike struct {
	// contains filtered or unexported fields
}

Zernike is a magnitude-based perceptual hash built from Zernike moments.

The descriptor stores |A(n,m)| values for all valid orders up to a maximum degree (excluding A(0,0)). Magnitude makes the hash rotation-invariant.

Based on A. Khotanzad and Y. H. Hong, "Invariant Image Recognition by Zernike Moments" (1990).

func NewZernike added in v2.3.0

func NewZernike(opts ...ZernikeOption) (Zernike, error)

NewZernike creates a new Zernike hash with the given options. Without options, sensible defaults are used.

func (Zernike) Calculate added in v2.3.0

func (z Zernike) Calculate(img image.Image) (hashtype.Hash, error)

Calculate returns a perceptual image hash.

Example
img, err := imghash.OpenImage("assets/cat.jpg")
if err != nil {
	panic(err)
}
z, err := imghash.NewZernike()
if err != nil {
	panic(err)
}
hash, err := z.Calculate(img)
if err != nil {
	panic(err)
}

fmt.Println(hash)

func (Zernike) Compare added in v2.3.0

func (z Zernike) Compare(h1, h2 hashtype.Hash) (similarity.Distance, error)

Compare computes the L2 (Euclidean) distance between two Zernike hashes.

type ZernikeOption added in v2.3.0

type ZernikeOption interface {
	// contains filtered or unexported methods
}

ZernikeOption configures the Zernike hash algorithm.

Directories

Path Synopsis
Package hashtype implements data types used to represent hashes.
Package hashtype implements data types used to represent hashes.
internal
imgproc
Package imgproc provides low-level image processing primitives used by the perceptual hashing algorithms in the parent package.
Package imgproc provides low-level image processing primitives used by the perceptual hashing algorithms in the parent package.
Package similarity implements data types and methods used to calculate similarities between hashes.
Package similarity implements data types and methods used to calculate similarities between hashes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL