Downloading Product Images With Perceptual Hashing

Images break the habits text taught you

Text records dedupe on a key. Normalise a SKU, hash it, done. Product images don’t work that way. The same photo of the same kettle shows up on six retailers at six sizes, three formats and two crops, with one of them carrying a watermark. Every copy has a different URL and different bytes. A byte hash says they’re six different images. A person says they’re one.

That gap is why image collection needs its own design. If you store every copy, a catalogue crawl across a few dozen retailers turns into a bucket that grows far faster than the product count, full of files nobody can tell apart. If you dedupe too aggressively, you merge the blue kettle into the red one, because the photos differ only in colour.

This walkthrough covers the whole path: choosing which image URL to fetch, downloading without hammering anyone, exact deduplication with a content hash, near-duplicate detection with perceptual hashes, finding matches quickly once you have millions of hashes, and a storage layout that keeps costs sane. The earlier deduplication pieces dealt with text records. The ideas carry over, but the matching step is completely different.

A quick scope note before the details. Product images are almost always copyrighted by the retailer, the brand or a photographer. Collecting them for matching, monitoring or internal analysis is a different activity from republishing them. This piece is about the first. If your plan involves showing collected images publicly, check the rights question separately before you build anything.

Finding the image you actually want

A product page rarely has one image URL. It has a gallery, thumbnails, zoom versions, a srcset with several widths, maybe a picture element offering WebP and AVIF alongside JPEG, and often structured data listing yet another URL.

Decide what you want first. For deduplication and matching, you want one canonical image per gallery slot, at a size big enough to hash reliably and small enough to be cheap. You rarely need the zoom version.

Sources, roughly in order of preference:

  • Structured data. Product markup often includes an image field with the main image URL. It’s the site telling you which image it considers primary.
  • The srcset on the main gallery image. Pick the largest width below a ceiling you set, rather than the absolute largest, which might be a very large zoom file.
  • Open Graph tags. og:image usually points at a decent-size version of the main image, though sometimes it’s a cropped social card.
  • The src attribute, which is often a small placeholder or a lazy-load stub on modern sites.

Watch for lazy loading. Many galleries put the real URL in a data-src or data-srcset attribute and a tiny placeholder in src. If your parser takes src, you’ll download a thousand identical grey squares, and your deduplication will cheerfully merge them all.

Look at the URL pattern too. Many retailers serve images from a CDN that resizes on request, with width or quality in the path or query string. If you can see that pattern, you can ask for a consistent size across all products on that site, which makes later hashing more consistent and the files smaller. Stay within the sizes the site itself uses on its pages, though. Requesting unusual sizes can force the CDN to generate new variants, which puts load on their side for no good reason.

Downloading without being a nuisance

Images are heavy. A product page’s HTML might be tens of kilobytes; its gallery can be many times that. On a catalogue crawl, image traffic can easily dwarf page traffic, and that has consequences for the site and for your own bill.

Fetch images in a separate queue from pages. Pages feed discovery and extraction and usually need to be fresh. Images mostly don’t change once published, so they can wait, run at lower concurrency and back off harder on errors. Separate queues also let you pause image fetching without stopping the crawl.

Respect the host’s limits. Image CDNs are usually built for heavy traffic, but they’re still somebody’s infrastructure. Keep a per-host concurrency cap, honour Retry-After on 429 and 503 responses, and don’t retry a 404 image every day forever. Mark it dead and check it rarely.

Think about routing. If page fetches go through a metered proxy pool, sending image downloads through the same pool can multiply the bandwidth bill. Many image CDNs serve the same files to any client without the checks the main site applies, so test whether image hosts need the same route as the pages. If they don’t, fetch them directly or through a cheaper path. If they do, your bandwidth cost per product just went up, and you should know that before the invoice arrives. The piece on blocking images in a headless browser covers the other side of this: when you render pages, block images there and fetch the ones you actually want separately, once.

Use conditional requests on refetch. If you store the ETag or Last-Modified from the first download, a later check can ask the server whether the image changed and get a tiny 304 reply instead of the whole file.

Record the response headers with each download: content type and length, plus any caching headers. You’ll use them for validation and for deciding when to recheck.

Validate the file before you hash it

Downloads fail in quiet ways. A CDN returns an HTML error page with a 200 status. A hotlink-protection rule serves a “no hotlinking” placeholder image. A timeout cuts the file off halfway, leaving a truncated JPEG that some decoders will open and render with a grey bottom half.

Check each download before it goes anywhere:

  • The content type is an image type, and the file’s magic bytes agree with it.
  • The file decodes fully. With Pillow, Image.open() followed by verify() catches many corrupt files; a full load() catches more.
  • The dimensions are above a floor you choose. Tiny images are usually placeholders or icons.
  • The file size matches Content-Length when that header was sent.

Keep a small list of known placeholder hashes. Every site that lazy-loads or hotlink-protects tends to serve the same placeholder to everyone, and once you’ve seen it you can reject it on sight.

Store the rejection reason when a file fails. A spike in “decoded as HTML” from one domain usually means their image host started blocking something, and you’d rather learn that from a count than from a gallery of broken thumbnails.

Exact duplicates first: a content hash

Before any perceptual work, do the cheap thing. Take a SHA-256 of the file bytes. Identical bytes mean an identical file, with no judgement involved.

This catches more than you might expect. Many retailers pull product images from the same manufacturer feed and serve them unchanged. The same file appears under different URLs on different sites, and a content hash collapses them in one step.

Use the content hash as the storage key. Content-addressed storage means you write each unique file exactly once, under a path derived from its hash, such as images/ab/cd/abcd1234....jpg. A second download of the same bytes finds the object already there and skips the write. The mapping from product and URL to image lives in your database, as rows pointing at hashes.

That separation matters. The image store only ever holds unique files. Everything about where an image came from, which product it belongs to and when it was seen lives in a table that’s cheap to update and query.

The content hash also makes refetching cheaper to reason about. If a retailer’s image URL returns the same hash as last time, nothing changed. If it returns a new hash, something did, and that’s worth recording, because a changed product image sometimes means a changed product.

What perceptual hashing does

A perceptual hash is a short fingerprint, typically 64 bits, computed from what an image looks like rather than its exact bytes. Two images that look alike produce hashes that differ in only a few bits. You compare two hashes by counting the differing bits, the Hamming distance. Small distance means visually similar.

There are several common algorithms, and the Python imagehash library implements the main ones:

  • Average hash (aHash). Shrink the image to a tiny greyscale grid, compare each pixel to the mean, and set a bit for above or below. Fast and simple, and sensitive to brightness changes.
  • Difference hash (dHash). Shrink the image, then compare each pixel with its neighbour. It captures gradients, so it copes better with overall brightness shifts.
  • Perceptual hash (pHash). Shrink the image, run a discrete cosine transform, keep the low-frequency coefficients, and compare them with their median. It focuses on overall structure and is generally more tolerant of compression and small edits, at a bit more compute cost.
  • Wavelet hash (wHash). Similar in spirit to pHash, using a wavelet transform instead.

All of them start by shrinking the image and discarding colour. That’s what makes them tolerant of resizing, recompression and format changes. It’s also exactly why they struggle with colour variants, which we’ll come to.

Which one to use isn’t a question we’ll answer with made-up accuracy figures. The practical approach is to compute two, commonly pHash and dHash, store both, and pick thresholds by testing on labelled pairs from your own catalogue. Storage cost is trivial, 8 bytes each per image, and having two signals helps with the awkward cases.

Picking a threshold without guessing

The whole system turns on one number: the Hamming distance below which two images count as the same. Too high and different products merge. Too low and obvious copies stay separate.

Don’t borrow a threshold from a blog post, including this one. The right value depends on your images, your hash choice and what “the same” means in your use case. Build a labelled set instead.

Take a few hundred image pairs from your real data. Include pairs you know are the same image in different sizes and formats, pairs that are the same product photographed differently, pairs of colour variants, and pairs of unrelated products from the same retailer that share a white background and a centred layout. Label each pair with what you want the system to decide.

Compute the distance for every pair, and look at the distribution for each label. You’ll usually see a cluster of small distances for true copies, a spread of large distances for unrelated products, and an awkward middle where crops, watermarks and colour variants live.

Pick a threshold that sits in the clean gap if there is one. If there isn’t, use two thresholds: below the lower one, merge automatically; above the upper one, keep separate; in between, flag for a second check. That middle band is where most of the interesting work happens, and pretending it doesn’t exist is how catalogues end up with merged variants.

Rerun the labelled set whenever you change hashing code, image sizes or source sites. A threshold that worked on one retailer’s photography can behave differently on another’s.

The cases that fool perceptual hashes

Knowing where hashes fail is more useful than knowing where they work.

Colour variants. The same kettle in red and blue, photographed identically, produces nearly identical greyscale thumbnails. Perceptual hashes see them as the same image. For product catalogues this is the most important failure, because merging variants is a real data error. The fix is a colour check on candidate matches: compare colour histograms or average colour in a few regions, and refuse to merge when they differ strongly.

Templated photography. Many retailers shoot every product on the same white background, centred, at the same angle. Two different small items can end up with similar hashes because most of the image is identical background. Cropping to the content before hashing, by trimming uniform borders, helps a lot.

Crops and padding. One site shows the full photo, another crops it square, a third pads it into a wide banner. Standard perceptual hashes aren’t crop-invariant, so the distance can jump. Trimming borders before hashing handles padding. Real crops are harder; a feature-based matcher can help in the middle band if it matters enough.

Watermarks and overlays. A “SALE” badge in a corner or a retailer logo changes a small area of the image. Small overlays often shift the hash only a little. Large ones can push it past your threshold.

Mirrored images. Some sites flip product photos. Hashing both the image and its mirror, and taking the smaller distance, catches that if you care about it.

Placeholder images. Already covered in validation, but worth repeating: a missed placeholder will attract hundreds of false matches, because every product with that placeholder “looks the same”.

Finding near matches at scale

Comparing a new hash against every stored hash is fine for thousands of images and far too slow for millions. You need an index that finds hashes within a small Hamming distance without scanning everything.

A BK-tree is the classic structure. It organises items by distance so a search can skip whole branches that can’t contain a match. It’s simple to implement and works well at moderate scale, though it lives in memory and gets slower as the search radius grows.

The multi-index approach scales further and fits in a normal database. Split each 64-bit hash into several chunks, say four chunks of 16 bits. If two hashes are within a distance smaller than the number of chunks, at least one chunk must match exactly, by the pigeonhole principle. So you index each chunk as an ordinary column, look up candidates that share any chunk exactly, then compute the full distance on that small candidate set.

In SQL terms, that’s four indexed integer columns and a query that ORs four equality conditions, followed by a Hamming distance check in the application or with a bit-count function if your database has one. Postgres can do this comfortably, and it means your image index lives beside the rest of your catalogue data.

There are also dedicated vector and similarity search tools that support binary hashes. They’re worth a look if you’re doing this at very large scale or also matching with learned image embeddings. For most catalogue work, the chunked index in the database you already run is enough.

Whatever structure you use, search before you store. When a new image arrives, look for near matches first, then decide whether it joins an existing image cluster or starts a new one.

Clusters, not pairs

Once you’ve found near matches, you need a model for what “the same image” means across your whole collection. Pairwise decisions aren’t enough, because similarity isn’t transitive. Image A might be close to B, and B close to C, while A and C are far apart. Chain enough of those together and you merge things that shouldn’t be merged.

Model groups of matching images as clusters with a representative. When a new image arrives, compare it against cluster representatives rather than every member. If it’s within threshold of one representative, and passes the colour check, it joins that cluster. If it matches none, it becomes a new cluster with itself as representative.

Choose the representative on purpose. The largest clean version, without watermarks or overlays, from the most authoritative source, is usually the one you want to keep and show. Record why it was chosen, so you can change the rule later.

Keep every member’s metadata even if you only keep one file. The row that says “retailer X showed this image for product Y on this date” is still useful, even when the pixels are stored once. That’s what lets you answer questions like which retailers use the manufacturer’s photo and which shot their own.

Make merges reversible. Store cluster membership as rows, not as a destructive rewrite. When someone finds that a cluster merged two colour variants, you should be able to split it and reassign members without re-downloading anything.

A worked example: one kettle, four retailers

Walk one product through the pipeline to see where each step earns its place.

A kettle is sold by four retailers. Retailer one and retailer two both use the manufacturer’s feed, and serve the same JPEG from their own CDNs under different URLs. Retailer three uses the same photo, re-encoded as WebP at a smaller width, with a “free delivery” badge in the corner. Retailer four shot its own photo on a grey background from a slightly different angle. The kettle also comes in two colours, and every retailer shows both.

The URL selector picks the main gallery image for each colour on each site, using structured data where it’s present and the srcset otherwise. That’s eight downloads.

Validation passes all eight. The content hash collapses retailer one and two’s files for each colour, because the bytes are identical. Six unique files remain.

Perceptual hashing runs on the trimmed images. Retailer three’s WebP lands a small distance from the manufacturer’s JPEG of the same colour, despite the resize, the format change and the badge. Below the lower threshold, and the colour check agrees, so it joins that colour’s cluster automatically.

Retailer four’s own photo lands in the middle band. Same product, different shot. It’s flagged for a second check, which in this pipeline means a feature-based comparison plus a look from a person on a review screen. The decision is recorded either way.

The two colour clusters sit very close in perceptual distance, because the greyscale thumbnails barely differ. The colour check refuses the merge, so they stay separate. Without that check, this is the step where the red kettle would have quietly become the blue one.

At the end, storage holds six files, one per unique byte sequence, and the database holds eight sightings pointing into two clusters plus one pending decision. The representative for each cluster is the manufacturer’s full-size JPEG without a badge.

Using clusters to match products across retailers

Image clusters are useful beyond saving storage. They’re one of the stronger signals for matching the same product across retailers when identifiers don’t line up.

Product matching usually starts with identifiers: GTINs, manufacturer part numbers, model numbers in titles. Those are often missing, inconsistent or formatted differently. An image cluster that spans several retailers is independent evidence that their listings show the same thing.

Treat it as evidence, not proof. Two retailers can use the same manufacturer photo for different pack sizes, or for a bundle and a single item. A shared image cluster raises the likelihood that listings match; it doesn’t settle it. Combine it with title similarity, brand, price range and whatever identifiers you do have.

Clusters also reveal things about the listings themselves. Retailers that share the manufacturer’s image are probably pulling from the same feed, which tells you something about how their catalogues are built. A retailer that shot its own photos might have handled the product physically. Neither is a quality judgement, but both are facts a catalogue analyst may care about.

Keep the matching layer separate from the image layer. The image pipeline answers “do these images look the same”. Product matching answers “are these listings the same product” and uses image clusters as one input among several. Mixing the two makes both harder to debug, because a wrong product match could come from a bad image merge or from bad title logic, and you want to know which.

A storage layout that stays affordable

Unique files, stored once, under content-hash keys, is most of the answer. A few more choices keep the bucket from creeping up.

Store originals once. Resist the urge to re-encode on ingest. Converting everything to one format saves some space but loses the original bytes, which you may need to prove what a site served. If you want smaller files, generate derivatives.

Generate derivatives lazily. A thumbnail for a review UI and a normalised image for hashing are both derivatives. Create them when needed, store them under their own prefix keyed by source hash and size, and let a lifecycle rule expire rarely used ones. They can always be regenerated from the original.

Put cold originals in a cheaper storage class. Most product images are read rarely after ingestion. Object storage lifecycle rules can move objects to infrequent-access or archive tiers after a period, which the lifecycle-rules piece covers in more detail. Leave the representatives of active clusters in the standard tier if your application reads them often.

Decide what not to keep. For some uses, you don’t need every cluster member’s file at all, only the representative plus metadata rows for the rest. If a member is a byte-level duplicate or a smaller version of the representative, dropping its file loses nothing.

Keep the database lean too. Per image, you need the content hash, perceptual hashes, dimensions, format, byte size, cluster ID and first and last seen dates. Per sighting, you need the product, the page and image URLs, the content hash and the date. That’s a small amount of data per row, even across millions of sightings.

Keeping it fresh without re-downloading everything

Product images change less than prices, but they do change. A retailer reshoots a range, a brand refreshes packaging, a listing swaps in a lifestyle photo. You want to notice without downloading the whole catalogue’s images every week.

Start with the page. If the image URL on the product page hasn’t changed since the last crawl, the image probably hasn’t either. Many CDNs put a version or hash in the image URL, so a new image usually means a new URL.

When the URL is the same, use a conditional request. A 304 reply costs almost nothing and confirms the file is unchanged. Only download when the server says it changed or doesn’t support conditional requests.

Schedule image rechecks separately from page crawls, and less often. The page crawl tells you when an image URL changes; the image recheck mostly catches in-place replacements, which are rarer.

When a product’s image changes, keep the old one. Treat it as a new sighting that points at a new hash, with the old sighting’s last-seen date closed off. A history of image changes can be useful, for example to see when a product was repackaged.

Watch the ratio of new clusters to new sightings over time. A sudden rise in new clusters from one site can mean they reshot their catalogue, or that your URL selection started picking up a different image, like a lifestyle photo instead of the packshot. Either way, it’s worth a look.

Mistakes that show up in the first month

A few problems appear so often they’re worth listing plainly.

Downloading placeholders. The parser reads src on a lazy-loaded gallery, and a large share of your images turn out to be the same grey square. Check data-src and friends, and keep the placeholder hash list.

Merging colour variants. The hashes match, the threshold says merge, and now red and blue share an image. Add the colour check before any automatic merge.

Hashing untrimmed images. White borders and padding dominate the tiny greyscale grid, so different products look alike and the same product with different padding looks different. Trim uniform borders first.

Routing images through an expensive pool by default. The bandwidth bill jumps and nobody knows why until someone reads the proxy dashboard. Test whether image hosts need the same route as pages.

Re-encoding originals on ingest. It saves space and loses the original bytes, and the saving is usually smaller than the cost of storing derivatives separately.

Threshold by folklore. A number copied from somewhere else works on the sample you looked at and fails on the next retailer. Build the labelled set.

What to build on Monday

Here’s an order that gets a working image pipeline without painting yourself into a corner.

Write the URL selector per site: structured data first, then the largest srcset entry under a ceiling, then og:image, with lazy-load attributes handled. Test it on twenty products per site and look at what it picks.

Put image downloads in their own queue with per-host limits, backoff and conditional requests, and decide which route they take.

Validate every file: type, magic bytes, full decode, minimum size, placeholder list.

Store originals under SHA-256 keys, write once, with sightings in a database table.

Trim borders, then compute pHash and dHash for every unique image. Store both.

Build a labelled set of a few hundred pairs, including colour variants and templated shots, and choose two thresholds with a middle band.

Index hashes in chunks for near-match search and match new images against cluster representatives. Add the colour check before any merge, and keep cluster membership reversible.

Add lifecycle rules for derivatives and cold originals.

Most of this is ordinary engineering. The judgement lives in the thresholds and the colour check, and that’s where it’s worth spending time with real images from your real sources.

If you’re building catalogue collection at scale and want more on the crawling, storage and proxy side of it, the rest of our guides are at Data Research Tools.

Get new guides and videos first — join the Telegram channel.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *