Cleaning

How perceptual hashing finds near-duplicate images

The short answer

A perceptual hash shrinks an image to a tiny fingerprint of its overall pattern of light and dark. Resized, re-saved or lightly edited copies get nearly the same fingerprint, even though their bytes are completely different. You measure the distance between two fingerprints, by counting differing bits (Hamming) or with a Euclidean distance, and treat anything under a threshold as a near-duplicate. A cryptographic hash like SHA-256 can't do this: change one byte and the whole hash changes.

Real image folders rarely contain perfect copies. The same picture turns up as a PNG and a JPEG, full size and as a thumbnail, with and without a small logo. Each is a different file, but to you it's the same image.

Perceptual hashing is the standard way to catch them. This guide uses the exact methods in our duplicate image finder, including where they differ from the textbook versions, so the tool's threshold numbers make sense.

Why SHA-256 only catches identical files

A cryptographic hash such as SHA-256 reads every byte of a file and produces a 256-bit value that changes completely if even one bit does. That's ideal for verifying a download and useless for spotting a resized copy: re-saving a JPEG at a slightly different quality changes thousands of bytes, so the two hashes share nothing.

Our tool still runs SHA-256 first. It removes files with identical bytes, such as the same download saved twice, before any visual comparison. It's fast and practically never wrong. Anything re-encoded, resized, cropped or with edited metadata gets past it. A perceptual hash catches those.

Average hash, step by step

The average hash (aHash) is the simplest perceptual hash. In its Average Hash + Hamming mode, our tool does this:

  1. Shrink. Draw the image onto a small square canvas, 8×8 pixels by default. The aspect ratio is ignored, and all fine detail disappears on purpose.
  2. Convert to grayscale. Each pixel becomes one brightness value: 0.3 × red + 0.59 × green + 0.11 × blue.
  3. Average. Compute the mean brightness of all the pixels.
  4. Threshold. Each pixel becomes 1 if it's brighter than the mean and 0 otherwise. At 8×8, that gives a 64-bit fingerprint.

Here's a toy 4×4 example. The numbers are made up for illustration; real hashes use 8×8 or more.

Image A: brightness (0-255)     Bits (mean = 112.5)
200  190   60   50              1 1 0 0
210  180   70   40              1 1 0 0
120  110  100   90              1 0 0 0
 30   40  150  160              0 0 1 1

The 16 values add up to 1,800, so the mean is 112.5. Row by row, the hash is 1100 1100 1000 0011.

Now take a copy that was re-saved and brightened slightly. Every value rises by about 10, with a little compression noise on top:

Image B: brightened copy        Bits (mean = 122.6)
211  199   72   58              1 1 0 0
222  188   81   49              1 1 0 0
129  125  108  101              1 1 0 0
 38   52  158  171              0 0 1 1

Because the mean rises with the pixels, only one bit flips. The pixel that read 110 sat just under A's mean, and in B it reads 125 against a mean of 122.6. Pixels close to the average are the fragile part of any average hash.

How an average hash is made from 16 pixelsEach of 16 brightness values is compared with their mean of 112.5: brighter becomes 1, otherwise 0, giving the hash 1100 1100 1000 0011.1 · Brightness of 16 pixels2 · Above the mean?200119016005002101180170040012011100100090030040015011601mean 112.5hash: 1100 1100 1000 0011
The toy example from the text, with made-up numbers. A real hash uses an 8 × 8 thumbnail: 64 bits.

Comparing hashes with Hamming distance

The Hamming distance between two hashes is the number of positions where the bits differ. A and B differ in 1 bit out of 16. Now flip image A left to right:

Image A, mirrored               Bits (mean = 112.5)
 50   60  190  200              0 0 1 1
 40   70  180  210              0 0 1 1
 90  100  110  120              0 0 0 1
160  150   40   30              1 1 0 0

Same pixels, same mean, but the hash is now 0011 0011 0001 1100: 14 of 16 bits differ from A. Two random 16-bit hashes differ in about 8, so to the hash the mirrored copy looks less like A than an unrelated image. That's the biggest blind spot of this family of methods.

In the tool, the default Hamming threshold of 5 means "no more than 5 of 64 bits differ" at 8×8. The count is absolute, so at 16 px (256 bits) the same 5 is far stricter.

DCT hashing: keeping only the low frequencies

The average hash works on pixels. A DCT-based hash, often called pHash, first rewrites the thumbnail as a mix of smooth cosine patterns using the discrete cosine transform, the transform JPEG uses. Each coefficient says how much of one pattern the image contains. The top-left one is the overall average. Its neighbors describe broad changes such as "brighter on the left than the right", and coefficients further from that corner describe finer and finer detail.

What usually happens to copies (resizing, recompression, sharpening, noise) mostly disturbs fine detail, the high frequencies. The broad, low-frequency layout survives almost untouched, so a fingerprint of only the lowest frequencies makes copies agree while different pictures usually don't.

The classic recipe

A widely used version is the phash function in the open-source imagehash Python library. It shrinks the image to 32×32 grayscale, runs a 2D DCT, and keeps the top-left 8×8 block of coefficients. Each bit records whether a coefficient is above the block's median, giving a 64-bit hash compared by Hamming distance.

What our tool does differently

Our DCT + Euclidean mode starts the same way, but keeps the actual numbers instead of turning them into bits:

  1. Shrink to a square grayscale thumbnail, 32×32 by default (adjustable from 8 to 64).
  2. Run a 2D DCT (an orthonormal DCT-II along the rows, then along the columns).
  3. Keep the 8×8 block of lowest frequencies and drop the top-left average-brightness term, which leaves 63 coefficients.
  4. Normalize those 63 values: subtract their mean, then divide by their standard deviation.
  5. Compare two images by the Euclidean distance between their lists of 63 numbers.

Dropping the average term makes the hash ignore uniform brightness changes. Normalizing makes it ignore contrast changes, which scale every coefficient equally (clipping at pure black or white aside). And keeping real numbers avoids the bit-flipping fragility you saw with the 110 pixel above.

One row, worked through

The tool works on a 32×32 grid, but a single row of eight brightness values is enough to watch the transform at work. Row A runs from bright on the left to dark on the right: 200 200 180 120 60 40 40 40. We ran it, a brightened copy and a higher-contrast copy through the same orthonormal DCT the tool uses:

                 DC     1      2      3      4      5     6     7
Row A          311.1  189.7   31.5  -34.4  -14.1   4.6   2.2  -0.1
Row A + 30     396.0  189.7   31.5  -34.4  -14.1   4.6   2.2  -0.1
Row A x 1.2    373.4  227.7   37.9  -41.3  -17.0   5.5   2.7  -0.1

Adding 30 to every pixel moves only the DC term; the other seven numbers do not change at all. Multiplying by 1.2 scales every number by 1.2. Once the DC term is dropped and the remaining seven are normalized, all three rows become the same list, 2.36 0.08 -0.86 -0.57 -0.30 -0.34 -0.37, at a distance of exactly 0 from each other.

Coefficient 1 (189.7) dwarfs the rest because this row is mostly "bright on one side, dark on the other", and that broad shape is what the fingerprint remembers. Add a few points of noise to each pixel (203 198 183 118 62 37 41 39) and the normalized list moves by 0.07. Reverse the row and coefficient 1 becomes −189.7: the distance jumps to 5.2, close to the largest possible for seven numbers (√28 ≈ 5.3). That is the mirroring problem from the failure list below, in eight pixels.

Resolution matters less in this mode than you might think. Each coefficient describes a pattern relative to the whole image, such as "one and a half cycles from left to right", so the 63 coefficients mean the same thing at 16, 32 or 64 px. A larger thumbnail just estimates them more cleanly.

Hamming vs Euclidean distance

Hamming distance counts disagreeing bits, so it only knows whether two values fell on the same side of a line. Euclidean distance is the straight-line distance between two lists of numbers (square each difference, add them up, take the square root), so it also knows how far apart the values are.

Our Euclidean modes normalize both lists to mean 0 and standard deviation 1 first, which gives the distance a neat meaning. For two lists of N numbers with correlation r (1 = same pattern, 0 = unrelated, −1 = opposite), it works out to exactly:

distance = √(2 × N × (1 − r))

DCT mode always compares N = 63 numbers, so every threshold maps to a minimum correlation:

ThresholdMinimum correlationWhat it tends to catch
20.97Re-saves, format changes, resized copies, brightness tweaks
3 (tool default)0.93Plus most very small crops
40.87Plus some light crops and tilts; chance matches begin
60.71Heavier edits, with many more false groups
100.21Anything with a vaguely similar layout
16 or moreanyEverything (the largest possible distance is about 15.9)

Despite its name, the Average Hash + Euclidean mode doesn't make bits at all. It normalizes the grayscale thumbnail itself and compares that, so N is the number of pixels: 64 at 8 px, 256 at 16 px, 1,024 at 32 px. Its default threshold of 3 therefore asks for a correlation of about 0.93 at 8 px, 0.98 at 16 px and 0.996 at 32 px: in this mode, a higher resolution makes the same threshold much stricter. Switching method resets both sliders to that method's defaults.

Bit counts and what they hide

If the 64 bits of an average hash behaved like coin flips, two unrelated pictures would land within 5 bits of each other about once in 2.2 trillion pairs (we computed 4.5 × 10−13 from the binomial distribution). Real collections come nowhere near that. The bits are tied together by layout: a sky fills the top rows with 1s, a dark foreground fills the bottom rows with 0s, and thousands of landscapes share that pattern. The first FAQ below has two unrelated images just 1 bit apart. Read a Hamming threshold as "how similar is the layout", never as odds of a false match.

The tool's Hamming threshold is also an absolute count of bits, so the same share of disagreeing bits needs a different number at each Hash Resolution:

Hash ResolutionBits in the hashA threshold of 5 allowsThreshold with the same share as 5 of 64
4 px1631% of bits1
8 px (default)647.8%5
16 px2562.0%20
32 px1,0240.5%80 (out of reach: the slider stops at 64)

For comparison, Meta's PDQ hash (next section) suggests a starting threshold of 31 out of 256 bits, about 12%.

Other perceptual hashes you will meet

Average and DCT hashes are two members of a larger family. If you have used another duplicate finder or a Python script, it most likely ran one of these:

HashHow it worksStrengths and weak spots
Average hash (aHash)Each pixel of a small gray thumbnail is above or below the meanSimplest and fast; the most false matches of the group
Difference hash (dHash)Shrinks to 9×8 and records whether each pixel is brighter than its neighbor: 8 comparisons per row, 64 bitsAs fast as aHash with far fewer false matches in its author's tests
DCT hash (pHash)32×32, DCT, the 8×8 low frequencies, bits from the medianThe usual choice for resized and recompressed copies
Wavelet hash (wHash)Like pHash, with a wavelet transform in place of the DCTUsed for the same jobs as pHash
Color hashThe spread of hues plus the shares of black and gray, with no position informationSees color, which every grayscale hash ignores; blind to layout
Crop-resistant hashSplits the picture into regions and hashes each oneBuilt to survive crops, the weak spot of whole-image hashes
PDQ (Meta)DCT-based, 256 bits, plus a quality scoreBuilt for matching at large scale; featureless images can be filtered out by their score

The first six are all in the imagehash library linked above. Neal Krawetz described aHash and pHash on his blog in 2011 and dHash in a 2013 post, where he found dHash as fast as aHash and close to pHash in accuracy, while pHash was far slower in his test. Meta open-sourced PDQ in 2019. All of these end in bits compared by Hamming distance; our two Euclidean modes are the odd ones out.

A quick calibration run

To see real numbers, we re-implemented the DCT mode's steps in Python and ran them on 143 different photos from a desktop operating system's built-in wallpapers and screensavers, mostly aerial landscapes, plus scripted edits of each. Two caveats: this is one small set of photos, not illustrations, so your images will give different numbers; and our script resizes images slightly differently from a browser. Treat the figures as a rough guide to scale.

Copy compared with its originalMedian distance90% of copies under
Shrunk to 25% and re-saved as JPEG0.130.30
Brightness and contrast raised0.260.63
Cropped 3% on every side0.921.83
Cropped 8% on every side2.945.33
Rotated 5°3.114.58
Cropped 15% on every side5.378.52
Mirrored left to right6.6811.61

Between different photos the median distance was 9.9. About 1% of pairs came in under 3.8, about 4.5% under 5, and about half within 10. We also tried a wallpaper design that ships in four colors with identical shapes: its color versions measured 0.2 to 1.5 apart, because the hash only sees brightness.

Resizing, recompression and brightness changes barely register. Crops and rotation climb steadily, and a 15% crop drifts into the range of unrelated pictures. Mirrored copies sit among the unrelated photos, so no threshold catches them reliably. A threshold of 10 would have grouped half of all unrelated pairs. That's why the tool defaults to 3, where under 1% of unrelated pairs matched.

Choosing a threshold

A threshold trades missed copies against false groups. You review every group before saving, so a false group only costs time, while a missed copy stays in your set unnoticed. Very loose settings, though, create huge mixed groups that are slow to check. A practical approach:

  1. Start at the default of 3 in DCT mode. It catches re-saves and resized copies with few false matches.
  2. To catch cropped or edited copies as well, raise it one step at a time, press Reprocess and look at the new groups.
  3. Stop when new groups start mixing different pictures. In our test set that began around 4 to 5.

If your images share a strong common layout, such as characters centered on plain white backgrounds, even 3 may group different pictures. Drop to 2 in that case.

From distances to groups

A distance compares two pictures; a group needs a rule. Our finder makes one greedy pass in the order the files were added. The first file not yet in a group becomes an anchor, and every later ungrouped file within the threshold of that anchor joins it. Here is that rule on four files, with made-up DCT distances and the default threshold of 3:

PairA–BA–CA–DB–CB–DC–D
Distance2.13.62.81.52.41.0
  • Added as A, B, C, D: A anchors. B (2.1) and D (2.8) join it, C (3.6) does not. C is next, but B and D are already taken, so C lands in Unique Images even though it sits 1.0 from D.
  • Added as C, A, B, D: C anchors. B (1.5) and D (1.0) join it, and this time A (3.6) is the one left alone.

Same four files, two different results, and the file left over is always the one furthest from whoever anchored. You can turn this to your advantage. Since anchors are the earliest files, add your most trusted copies first: drop the folder of camera originals or full-size exports, then the chat downloads and thumbnails in a second drop. Each group's anchor is then usually the copy you want to keep, with the weaker copies gathered around it.

The anchor rule is there to prevent chaining. A rule of "join the group if you are close to any member" would link A to B to C to D across a run of small edits, and in a big folder such chains can join pictures that look nothing alike at the two ends. Measuring every member against the anchor keeps each group within one threshold of its first picture.

Failure modes to know about

  • Mirroring and rotation. A left-right flip reverses the sign of 32 of the 63 coefficients (those with an odd horizontal frequency). Unless the picture is fairly symmetric, or its main structure runs side to side like a horizon, the match is lost. Rotating by 90° or 180° is worse.
  • Crops, borders and padding. Anything that moves or rescales content within the frame shifts the low frequencies. Padding a wide image to a square is often enough to break a match.
  • Color. All three methods work in grayscale, so a recolored or grayscale copy looks the same to them.
  • Inversion. A negative, or a design's dark version with light and dark swapped, has a correlation near −1 with the original: the maximum distance.
  • Small local changes. A change in a small area, such as a different expression on the same drawing or a small signature, hardly moves the low frequencies. That's handy for finding alternates, but the hash can't tell them from true copies.
  • Meaning. A perceptual hash knows nothing about content. Two drawings of the same character are just different images.

Since the hash ignores uniform brightness and contrast changes, a white balance or histogram correction usually moves it only a little. Still, deduplicate before you run the batch color fixer, so you don't correct copies you're about to delete. Our dataset cleaning workflow shows where each step fits.

Perceptual hashes versus AI embeddings

Our Group Similar Images tool takes a different route to the same question. It runs each picture through CLIP ViT-B/32, an AI model that describes what a picture shows as a list of numbers, and groups pictures by how close those lists are (cosine similarity). Its strictest quick setting, Near-copies, groups pictures at 0.93 or above. We measured how edited copies score against their originals:

EditCLIP similarity to the original, mean (lowest)At Near-copies (0.93)
Half size0.997 (0.99)Grouped
Mirrored left to right0.987 (0.978)Grouped
Brighter0.970 (0.940)Grouped
Cropped to 85%0.964 (0.946)Grouped
Re-saved as JPEG at quality 300.951 (0.922)Usually; the worst copy fell below

The mirrored row is the one to notice. A flip that sends the DCT distance into the range of unrelated photos barely moves CLIP, because the model describes content rather than where the light and dark sit. In our near-copies test (40 photos plus 10 copies, 4 of them mirrored), all 10 copies joined their originals at 0.93 and no group mixed two different photos.

The hash still wins on cost. CLIP needs an 85 MB model download, spends about a quarter of a second on each picture in our tests, and the grouping page takes up to 4,000 pictures. A sensible split is to clear the bulk of copies with the duplicate finder, then run the keepers through Group Similar Images at Near-copies to catch the mirrored versions the hash cannot see.

Test the settings on your own pictures

The calibration figures above came from landscape photos. Your collection may behave differently, and ten minutes of testing tells you where its limits are:

  1. Copy ten pictures that are typical of the collection into a test folder.
  2. Make one edited copy of each, using a different edit each time: half size with Resize Image, a low-quality JPEG with Compress Image, a 5% crop with Crop Image, a mirrored copy with Rotate & Flip, and a brightness change in the color fixer. These tools add a suffix to the name (-cropped, the new size), which makes the copies easy to spot.
  3. Add 20 to 30 unrelated pictures from the same collection. They show you where false matches start.
  4. Load everything into the duplicate finder. Under Advanced settings, step the threshold through 2, 3, 4 and 5. Each change regroups when you release the slider.
  5. At each step, note which edited copies joined their original and whether any group holds two different pictures. The highest threshold with no mixed group is your setting.

Expect the mirrored copies to stay apart at every sensible setting. Treat that as a reminder to look for flips by eye or with the CLIP route above.

When the groups look wrong

SymptomLikely causeWhat to do
One big group of pictures that are clearly differentThreshold too loose for the collection, or a shared layout such as subjects centered on whiteChoose "Exact copies", or 2 under Advanced
Results stricter or looser than you expect from the first visitMethod, threshold and resolution are remembered in your browser from last timeClick a "How alike?" button, which sets all three to a known preset
Transparent PNGs group with each other or with dark picturesFully transparent areas usually read as black before hashingConvert them to JPEG on a white background with the image converter, then compare
A known copy is missing from its groupMirrored or cropped, or it matched an earlier anchor firstCheck the other groups and Unique Images, raise the threshold one step, or try the CLIP route
Fewer pictures on screen than files addedByte-identical copies are removed, non-images skipped, and files the browser cannot decode (RAW, HEIC in many browsers) left outConvert HEIC photos first; use a file hash for RAW files
Groups change after adding more filesEvery change regroups all files from scratch, in the new orderAdd everything, settle the settings, then review
Put this into practice

Group visually similar images with perceptual hashing. It catches resized, re-saved and lightly edited copies that file hashes miss. It runs in your browser. Open the Duplicate Image Finder.

Frequently asked questions

Can two completely different images get the same hash?

Yes. A 64-bit average hash squeezes a whole picture into very little information, and images with similar broad layouts collide. In our wallpaper test, a landscape photo and an abstract graphic that were both bright on the left and dark on the right differed in just 1 of 64 average-hash bits, with a DCT distance of 3.7. That's why the tool shows groups for review instead of deleting anything.

Does the file format matter, PNG vs JPEG?

Not for the perceptual hash. Files are decoded to pixels first, so a PNG and a JPEG of the same picture hash almost identically; only the SHA-256 pass cares about bytes. One catch: transparency is ignored and fully transparent areas usually read as black, so a transparent PNG may not match the same image flattened onto white.

Why not just compare full-size images pixel by pixel?

Copies are often different sizes, so the pixels don't line up. Even at the same size, compression noise changes most pixel values a little, and a one-pixel shift changes almost all of them. Raw pixel differences track perceived similarity poorly, and they're slow to compute for every pair.

How do I find every copy of one particular picture?

The duplicate finder groups everything at once, which is more than you need for one picture. Add the folder to our Search Images tool instead and press Find similar on that picture: every other picture is ranked by similarity, best first, with the picture itself at number 1. Because it uses the CLIP model, it also finds mirrored copies.