Class PerceptualHash
64-bit perceptual hashes: images that look alike get hashes a few bits apart, however they were compressed or resized, so the Distance(ulong, ulong) between two hashes says how alike two pictures are. Store the hashes as keys to find near-duplicates.
public static class PerceptualHash
- Inheritance
-
PerceptualHash
- Inherited Members
Examples
// Find near-duplicate photos: hash each once, store the 64-bit keys, and call a pair a duplicate within about 10 bits.
ulong a = PerceptualHash.Dct(original), b = PerceptualHash.Dct(copy), c = PerceptualHash.Dct(other);
bool duplicate = PerceptualHash.Distance(a, b) <= 10;
bool unrelated = PerceptualHash.Distance(a, c) > 10;
string key = a.ToString("x16", System.Globalization.CultureInfo.InvariantCulture);
Remarks
Both hashes look at the first frame's brightness only, after flattening it onto white. The bits are in reading order, the
first in the most significant bit, so hash.ToString("x16") matches the hex string of Python's imagehash.
Methods
Dct(Raster)
Returns the DCT hash (pHash style; Zauner 2010): the image's brightness reduced to 32 × 32, a 2D DCT-II, and one bit per coefficient of the top-left 8 × 8, set when it is above the median of those coefficients without the DC term. It survives recompression, resizing and small brightness changes; pairs of unrelated photos are about 32 bits apart.
public static ulong Dct(Raster image)
Parameters
imageRasterThe image.
Returns
- ulong
The hash.
Exceptions
- ArgumentNullException
imageis null.- ObjectDisposedException
The image has been disposed.
Difference(Raster)
Returns the difference hash (dHash; Krawetz 2013): the image's brightness reduced to 9 × 8, and one bit per pair of horizontal neighbours, set when the right one is brighter. Faster than Dct(Raster) and a little less robust.
public static ulong Difference(Raster image)
Parameters
imageRasterThe image.
Returns
- ulong
The hash.
Exceptions
- ArgumentNullException
imageis null.- ObjectDisposedException
The image has been disposed.
Distance(ulong, ulong)
Returns the number of bits in which two hashes differ (their Hamming distance), 0 to 64.
public static int Distance(ulong a, ulong b)
Parameters
Returns
- int
The distance: 0 to about 10 for the same picture, around 32 for unrelated ones.