Build a Perceptual Duplicate Image Finder
A CLI that scans an image folder, computes a perceptual hash for each file, groups near-duplicates by Hamming distance, and reports clusters without deleting anything.
Project goal
Build a CLI that computes a perceptual hash for every image in a directory, groups images whose hashes fall within a distance threshold, and prints clusters of likely duplicates.
Final features
- Compute a perceptual hash for each image using a downscaled grayscale comparison.
- Compare hashes by Hamming distance and cluster images under a threshold.
- Tune the threshold from the command line and explain its effect.
- Report clusters with image counts and sizes, never deleting files.
- Skip non-image files and report how many were considered.
Architecture
A hasher produces a compact bit string for an image; a comparator computes Hamming distance and clusters by union-find; a reporter prints groups; and the CLI wires discovery to hashing to clustering. Hashing is isolated behind the image adapter so clustering is tested with synthetic hashes and no real decoding.
Prerequisites
- Node.js 20 LTS or later
- Familiarity with binary data and bit operations
- Basic understanding of perceptual hashing
Dependencies
- node >=20 — File traversal and the CLI entry point
- sharp ^0.33.0 — Decoding and downscaling images for hashing
- vitest ^2.1.0 — Clustering and distance tests
Directory structure
dup-images/
├── src/
│ ├── discover.js
│ ├── hash.js
│ ├── cluster.js
│ ├── report.js
│ └── cli.js
├── test/
│ ├── cluster.test.js
│ └── hash.test.js
└── package.json
Phases
1. Discovery
Walk the input directory and collect image files with their sizes and extensions.
Files: src/discover.js
import { readdir, stat } from 'node:fs/promises';
import { join, extname, relative } from 'node:path';
const SUPPORTED = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
export async function discover(root) {
const found = [];
async function walk(dir) {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) await walk(full);
else if (SUPPORTED.has(extname(entry.name).toLowerCase())) {
const info = await stat(full);
found.push({ path: full, rel: relative(root, full).replace(/\\/g, '/'), size: info.size });
}
}
}
await walk(root);
return found.sort((a, b) => a.rel.localeCompare(b.rel));
}Expected behavior: Nested directories yield supported images in a deterministic order, and an unsupported extension is ignored.
2. Perceptual hashing
Downscale an image to a small grayscale grid, compare against the mean, and emit a bit signature.
Files: src/hash.js
import sharp from 'sharp';
export async function hashImage(path, { size = 8 } = {}) {
const pixels = await sharp(path)
.greyscale()
.resize(size, size, { fit: 'fill' })
.raw()
.toBuffer();
const mean = pixels.reduce((sum, v) => sum + v, 0) / pixels.length;
let bits = '';
for (const value of pixels) bits += value >= mean ? '1' : '0';
return { bits, hex: BigInt('0b' + bits).toString(16).padStart((size * size) / 4, '0') };
}Expected behavior: The same image produces the same signature on repeated runs, and a re-saved copy at slightly lower quality produces the same or a very close signature.
3. Hamming distance and clustering
Compute Hamming distance between signatures and cluster near matches with union-find.
Files: src/cluster.js
export function hamming(a, b) {
let distance = 0;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) distance++;
return distance;
}
export function cluster(hashes, threshold) {
const parent = hashes.map((_, i) => i);
const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
const union = (a, b) => { parent[find(a)] = find(b); };
for (let i = 0; i < hashes.length; i++) {
for (let j = i + 1; j < hashes.length; j++) {
if (hamming(hashes[i].bits, hashes[j].bits) <= threshold) union(i, j);
}
}
const groups = new Map();
hashes.forEach((h, i) => {
const root = find(i);
if (!groups.has(root)) groups.set(root, []);
groups.get(root).push(h);
});
return [...groups.values()].filter((g) => g.length > 1);
}Expected behavior: Identical signatures have distance zero, and three mutually-near signatures end up in a single cluster.
4. Threshold selection
Map a user-facing similarity percentage to a Hamming threshold and validate the range.
Files: src/threshold.js
export function thresholdFromPercent(percent, bits = 64) {
const value = Number(percent);
if (!Number.isFinite(value) || value < 0 || value > 100) throw new Error('percent must be 0..100');
return Math.round((value / 100) * bits);
}
export function explain(threshold, bits = 64) {
return 'matching images may differ in up to ' + threshold + ' of ' + bits + ' bits';
}Expected behavior: A threshold of 10 percent on 64 bits returns 6, and a percent outside the range throws a clear error.
5. Reporter
Print clusters with their members, sizes, and relative paths, and summarise scan totals.
Files: src/report.js
export function formatClusters(clusters) {
return clusters.map((group, i) => {
const head = 'cluster ' + (i + 1) + ' (' + group.length + ' images)';
const items = group.map((g) => ' ' + g.rel + ' ' + g.size + ' bytes');
return [head, ...items].join('\n');
}).join('\n\n');
}
export function summarize(scanned, clusters) {
return 'scanned ' + scanned + ' images, found ' + clusters.length + ' duplicate clusters';
}Expected behavior: Each cluster prints a header with the member count followed by its files, and the summary reports the scanned total.
6. CLI and tests
Wire discovery, hashing, clustering, and reporting, and cover distance and clustering with tests.
Files: src/cli.js
import { discover } from './discover.js';
import { hashImage } from './hash.js';
import { cluster } from './cluster.js';
import { thresholdFromPercent, explain } from './threshold.js';
import { formatClusters, summarize } from './report.js';
const args = parse(process.argv.slice(2));
if (!args.dir) { console.error('usage: scan --dir <folder> [--similarity 10]'); process.exit(1); }
const files = await discover(args.dir);
const hashes = [];
for (const f of files) hashes.push({ ...f, ...(await hashImage(f.path)) });
const threshold = thresholdFromPercent(args.similarity ?? 10);
const clusters = cluster(hashes, threshold);
console.log(formatClusters(clusters));
console.log(summarize(files.length, clusters));
console.log(explain(threshold));Expected behavior: Scanning a folder with two near-duplicates prints one cluster and the summary, and a missing directory exits with code 1.
Testing
Run npx vitest. Distance tests assert that identical hashes have distance zero and a one-bit difference has distance one. Cluster tests feed synthetic hashes and assert that three mutually-near hashes form one cluster and a distant hash stays alone. A hash test runs against a fixture and asserts a stable 64-bit signature.
Troubleshooting
Resaved copies do not cluster together
Raise the similarity threshold a little and confirm the image is decoded before hashing; a threshold of zero only catches byte-identical files.
Unrelated images cluster together
Lower the threshold and consider a larger hash; with an 8x8 grid, visually different images can share many bits, so the threshold trades misses against false groupings.
Hashing is slow on a large collection
Cache hashes keyed by file size and modification time so unchanged files are not re-hashed on every run.
Deployment
Run as a maintenance job that reports clusters to a log or a file for review. The tool deliberately stops at reporting so that the decision to remove or move duplicates stays with a human.
Known limitations
- Perceptual hashes are good at catching resaves but miss images that were cropped or rotated.
- The pairwise comparison is quadratic in the number of images, which is fine for thousands but not millions.
Project overview
Exact duplicate detection is trivial; near-duplicate detection is the interesting problem, because the same photo resaved at a different quality is byte-different yet visually identical. Perceptual hashing collapses that difference into a small signature.
This tool computes a hash per image, compares hashes by Hamming distance, and clusters images that fall within a threshold. It only reports; it never deletes, which keeps the destructive step a human decision.
Clustering is union-find over distance comparisons, which is what makes it robust to chains where A matches B and B matches C:
export function cluster(hashes, threshold) {
const parent = hashes.map((_, i) => i);
const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
const union = (a, b) => { parent[find(a)] = find(b); };
for (let i = 0; i < hashes.length; i++) {
for (let j = i + 1; j < hashes.length; j++) {
if (hamming(hashes[i].hash, hashes[j].hash) <= threshold) union(i, j);
}
}
const groups = new Map();
hashes.forEach((h, i) => {
const root = find(i);
if (!groups.has(root)) groups.set(root, []);
groups.get(root).push(h);
});
return [...groups.values()].filter((g) => g.length > 1);
}
The chain-tolerance of union-find is the property that matters: a naive greedy grouping would split three related images into two clusters depending on order.
Setup
sharp is pinned because perceptual hashing depends on consistent downscaling, and a different resampling implementation could shift the hash.
| Dependency | Version | Why it is here |
|---|---|---|
| node | >=20 | File traversal and the CLI entry point |
| sharp | ^0.33.0 | Decoding and downscaling images for hashing |
| vitest | ^2.1.0 | Clustering and distance tests |
Create the project and install:
mkdir dup-images && cd dup-images
npm init -y
npm install sharp@^0.33.0
npm install -D vitest@^2.1.0
Configure the CLI and tests in package.json:
{
"name": "dup-images",
"type": "module",
"scripts": {
"scan": "node src/cli.js",
"test": "vitest run"
}
}
Commit a few tiny generated fixtures so hash tests run without large binaries in the repository.
Phase 1: Discovery
Walk the input directory and collect image files with their sizes and extensions. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.
import { readdir, stat } from 'node:fs/promises';
import { join, extname, relative } from 'node:path';
const SUPPORTED = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
export async function discover(root) {
const found = [];
async function walk(dir) {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) await walk(full);
else if (SUPPORTED.has(extname(entry.name).toLowerCase())) {
const info = await stat(full);
found.push({ path: full, rel: relative(root, full).replace(/\\/g, '/'), size: info.size });
}
}
}
await walk(root);
return found.sort((a, b) => a.rel.localeCompare(b.rel));
}
Acceptance for this phase: Nested directories yield supported images in a deterministic order, and an unsupported extension is ignored.
Phase 2: Perceptual hashing
Downscale an image to a small grayscale grid, compare against the mean, and emit a bit signature. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.
import sharp from 'sharp';
export async function hashImage(path, { size = 8 } = {}) {
const pixels = await sharp(path)
.greyscale()
.resize(size, size, { fit: 'fill' })
.raw()
.toBuffer();
const mean = pixels.reduce((sum, v) => sum + v, 0) / pixels.length;
let bits = '';
for (const value of pixels) bits += value >= mean ? '1' : '0';
return { bits, hex: BigInt('0b' + bits).toString(16).padStart((size * size) / 4, '0') };
}
Acceptance for this phase: The same image produces the same signature on repeated runs, and a re-saved copy at slightly lower quality produces the same or a very close signature.
Phase 3: Hamming distance and clustering
Compute Hamming distance between signatures and cluster near matches with union-find. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.
export function hamming(a, b) {
let distance = 0;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) distance++;
return distance;
}
export function cluster(hashes, threshold) {
const parent = hashes.map((_, i) => i);
const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
const union = (a, b) => { parent[find(a)] = find(b); };
for (let i = 0; i < hashes.length; i++) {
for (let j = i + 1; j < hashes.length; j++) {
if (hamming(hashes[i].bits, hashes[j].bits) <= threshold) union(i, j);
}
}
const groups = new Map();
hashes.forEach((h, i) => {
const root = find(i);
if (!groups.has(root)) groups.set(root, []);
groups.get(root).push(h);
});
return [...groups.values()].filter((g) => g.length > 1);
}
Acceptance for this phase: Identical signatures have distance zero, and three mutually-near signatures end up in a single cluster.
Phase 4: Threshold selection
Map a user-facing similarity percentage to a Hamming threshold and validate the range. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.
export function thresholdFromPercent(percent, bits = 64) {
const value = Number(percent);
if (!Number.isFinite(value) || value < 0 || value > 100) throw new Error('percent must be 0..100');
return Math.round((value / 100) * bits);
}
export function explain(threshold, bits = 64) {
return 'matching images may differ in up to ' + threshold + ' of ' + bits + ' bits';
}
Acceptance for this phase: A threshold of 10 percent on 64 bits returns 6, and a percent outside the range throws a clear error.
Phase 5: Reporter
Print clusters with their members, sizes, and relative paths, and summarise scan totals. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.
export function formatClusters(clusters) {
return clusters.map((group, i) => {
const head = 'cluster ' + (i + 1) + ' (' + group.length + ' images)';
const items = group.map((g) => ' ' + g.rel + ' ' + g.size + ' bytes');
return [head, ...items].join('\n');
}).join('\n\n');
}
export function summarize(scanned, clusters) {
return 'scanned ' + scanned + ' images, found ' + clusters.length + ' duplicate clusters';
}
Acceptance for this phase: Each cluster prints a header with the member count followed by its files, and the summary reports the scanned total.
Phase 6: CLI and tests
Wire discovery, hashing, clustering, and reporting, and cover distance and clustering with tests. The scope is chosen so the project is genuinely finishable, yet every phase has a real decision to make rather than busywork.
import { discover } from './discover.js';
import { hashImage } from './hash.js';
import { cluster } from './cluster.js';
import { thresholdFromPercent, explain } from './threshold.js';
import { formatClusters, summarize } from './report.js';
const args = parse(process.argv.slice(2));
if (!args.dir) { console.error('usage: scan --dir <folder> [--similarity 10]'); process.exit(1); }
const files = await discover(args.dir);
const hashes = [];
for (const f of files) hashes.push({ ...f, ...(await hashImage(f.path)) });
const threshold = thresholdFromPercent(args.similarity ?? 10);
const clusters = cluster(hashes, threshold);
console.log(formatClusters(clusters));
console.log(summarize(files.length, clusters));
console.log(explain(threshold));
Acceptance for this phase: Scanning a folder with two near-duplicates prints one cluster and the summary, and a missing directory exits with code 1.
Testing strategy
Run npx vitest. Distance tests assert that identical hashes have distance zero and a one-bit difference has distance one. Cluster tests feed synthetic hashes and assert that three mutually-near hashes form one cluster and a distant hash stays alone. A hash test runs against a fixture and asserts a stable 64-bit signature.
The transitive-cluster test is the one that catches naive implementations: the chain case is exactly where a pairwise greedy grouping gives the wrong answer.
Extending the project
A larger hash, colour hashing, and a cache of hashes keyed by file size and mtime are additions around the same pipeline. A move-to-duplicates action would be a distinct, explicit command rather than part of scanning.