Overview
Difference Hash (also known as dHash) is a perceptual hashing algorithm described by Dr. Neal Krawetz in “Kind of Like That”. Instead of comparing pixels to the mean, it compares adjacent pixels to capture horizontal gradients. This approach is more robust to brightness adjustments and better captures structural information than Average Hash.When to Use
Use Difference Hash when you need:- Better robustness than Average Hash
- Resistance to brightness changes and gamma correction
- Fast computation with low overhead
- Gradient-based features that capture image structure
- Good balance between speed and accuracy
Difference Hash is particularly effective at detecting images that differ only in brightness or exposure settings.
Constructor
Available Options
WithSize(width, height uint)- Sets the resize dimensions (hash is width × height bits)WithInterpolation(interp Interpolation)- Sets the resize interpolation methodWithDistance(fn DistanceFunc)- Overrides the default Hamming distance function
Supported Interpolation Methods
NearestNeighborBilinear(default)BicubicMitchellNetravaliLanczos2Lanczos3BilinearExact
Usage Example
With Custom Options
Default Settings
- Hash size: 64 bits (8 bytes)
- Resize dimensions: 8×8 pixels
- Interpolation: Bilinear
- Distance metric: Hamming distance
How It Works
The Difference Hash algorithm:- Resizes the image to (width+1) × height pixels (e.g., 9×8 for default)
- Converts to grayscale
- For each row, compares adjacent pixels from left to right:
- Sets bit to 1 if right pixel > left pixel
- Sets bit to 0 if right pixel ≤ left pixel
- Produces a width × height bit hash (64 bits by default)
Comparison
Difference hashes are compared using Hamming distance. Lower distances indicate more similar images.Advantages Over Average Hash
- More robust to brightness/exposure changes
- Better structural information through gradient comparison
- Similar computational cost
- Still very fast and simple
Performance
Difference Hash is slightly more expensive than Average Hash but still very fast:- Simple resize operation
- Single-pass gradient computation
- No mean calculation needed
- No complex transforms
References
- Kind of Like That by Dr. Neal Krawetz
- Source:
difference.go:11-13