Modern content based image retrieval (CBIR) works as nearest-neighbour search over learned embeddings. A neural network turns each image into a vector, an approximate nearest neighbour (ANN) index finds the vectors closest to the query, and the ranked neighbours come back as results. The embedding model decides the quality of those results. The vector database decides whether you can serve them at production latency. That leaves two engineering decisions: which index, tuned how, and which embedding model, general or fine-tuned. You settle both by measuring recall@k at the latency your product can afford.
How Content-Based Image Retrieval Evolved from Pixel Similarity to Embedding Search
The term “content-based image retrieval” dates from 1992, when Toshikazu Kato of Japan’s Electrotechnical Laboratory used it for experiments that retrieved images by the colours and shapes they contained. IBM’s QBIC (Query By Image Content) was the earliest commercial CBIR system. Initial CBIR systems searched by colour, texture and shape, and the most common comparison is a distance measure where 0 means an exact match on the dimensions considered. Colour histograms were among the most used features because they ignore image size and orientation.
From 2003, local descriptors (in practice SIFT) dominated retrieval research for more than a decade, because they cope well with image transformations. Feature learning began with AlexNet and ImageNet in 2012. By 2014, off-the-shelf CNN features showed a large gain over hand-crafted ones for recognition and retrieval. What the learned features addressed is the semantic gap: the distance between the concepts a person searches for and the low-level features computed from pixels. The descriptor-level detail of that shift, and how it plays out in face matching, sits in our explainer on how face recognition and pattern recognition work in computer vision.
Today networks such as ResNet and CLIP encode each image as a high-dimensional vector, and vector databases search those vectors with HNSW graphs, inverted file (IVF) indexes and product quantisation (PQ). The classical layer has not gone away, though. Our own engineering view is that most production vision pipelines still depend on classical features for steps such as image registration, which is part of the case for classical computer vision alongside deep models. What has changed is that learned features have replaced hand-designed ones as the dominant approach.
There is one more distinction to keep in mind, because it comes back when choosing a model. Instance-level retrieval looks for the same object or scene (one particular landmark, one particular product), while category-level retrieval looks for anything in the same class, and instance-level is the harder problem.
What Separates Classical CBIR from Text-Based Image Retrieval Today?
Classical CBIR and metadata search differ in what they analyse. Metadata search matches the keywords, tags and descriptions attached to an image. Content-based search analyses the pixels themselves. Searching by visual content costs more compute but is more efficient and reliable than searching by metadata.
CLIP places visual and textual meaning in one shared 512-dimensional space, so a text query and an image query go through the same vector index and only the encoder differs. In practice, then:
- Metadata search: sparse keyword retrieval over annotations, which finds only what someone labelled.
- Classical or deep CBIR (query by example): an image encoder, a vector index and a distance function, which finds what looks similar.
- CLIP-style text-to-image: a text encoder whose vectors share one space with the image embeddings, so text queries search the same index.
The open question with the third option is whether one embedding can serve both kinds of query well. That is a trade-off, covered below.
How Deep-Learning Embeddings and ANN Indexes Change Retrieval Latency and Recall
An embedding extractor is designed so that the distance between vectors reflects the similarity between the media they came from. That turns neighbourhood search in vector space into image similarity search. The catch is scale. The Faiss authors describe non-exhaustive search as the cornerstone of fast search once a collection grows past roughly 10,000 vectors. When you will run only a few thousand searches, exact “Flat” search is the efficient choice because the index build time is not amortised.
In the Frontiers benchmark, brute-force FAISS over 512-dimensional CLIP vectors stayed under 10 ms at 50,000 vectors, but all four systems tested scaled close to linearly, so million-scale collections would need IVF or PQ indexing to keep latency acceptable.
The ANN-Benchmarks study (Aumüller et al.) measures how recall trades against queries per second. A GPU IVF index answered around 655,000 queries per second at 0.7 recall but around 61,000 at 0.99 recall, roughly 20 to 30 times faster than the equivalent CPU structure. Graph-based methods gave the best performance on most datasets, with HNSW often the fastest, but they need long preprocessing to build. On one benchmark run, index build time ranged from about 2 seconds for FAISS-IVF to almost 5 hours for HNSW. So a collection that changes constantly pushes you towards IVF, even though HNSW wins at query time.
Retrieval papers show the same tension one level up. A deep image retrieval survey (Chen et al.) reports methods on Oxford-5k that answer in under 1 ms with mAP below 70%, against methods reaching 91% to 96% mAP at anywhere from 2 ms to 600 ms per query.
HNSW answered batched queries roughly 3 times faster at 0.5 recall and nearly 5 times faster at 0.99 recall than one query at a time. Faiss processes batched queries in parallel and recommends submitting queries in batches where possible.
Worked Example: HNSW Memory for an Image Catalogue
The Faiss guidance gives HNSW memory as (d × 4 + M × 2 × 4) bytes per vector, with M (links per vector) between 4 and 64. Assume 512-dimensional CLIP-class embeddings and M = 32. Each vector then takes 512 × 4 + 32 × 8 = 2,048 + 256 = 2,304 bytes. Ten million images need about 23 GB of RAM for the index, before any metadata. Halving M saves only 128 bytes per vector, because the raw float vectors dominate. To shrink the vectors themselves, product quantisation splits each vector into sub-vectors and quantises each separately. Faiss’s authors note that PQ often gives a good trade-off, which explains its wide adoption.
How Do You Tune recall@k Against p99 Latency When Choosing Between FAISS, ScaNN and HNSW?
First, the three names are not like-for-like. FAISS is a library that contains IVF, PQ and HNSW indexes. HNSW is a graph algorithm that also sits inside other engines (Qdrant and pgvector both use it). ScaNN is Google Research’s library built around anisotropic quantisation for maximum inner product search. So the real question is which index structure and parameters, in which serving system. The Faiss paper says plainly that the best of its dozen or so index types usually depends on the problem’s constraints. Its decision tree deals with memory, the hard constraint, first and only then with secondary trade-offs.
Recall@k is the share of the true nearest neighbours that appear in the k results returned. The knobs that move it are well defined:
- HNSW: M sets links per vector (more accuracy, more RAM), and efSearch sets the speed-accuracy trade-off at query time.
- IVF: nlist sets how finely the space is partitioned, and nprobe sets how many partitions each query scans. Raising nprobe recovers neighbours near cluster boundaries at a proportional latency cost.
- ScaNN: query time is dominated by the number of leaves and leaves searched, while indexing time depends on the quantisation threshold and block dimensions.
What the Measurements Say About Defaults
The Frontiers benchmark deliberately ran default production configurations rather than hand-tuned ones. Qdrant’s HNSW dropped to 0.88 on CIFAR-10 embeddings and to 0.82 to 0.84 on STL-10. The authors trace this to greedy graph traversal getting stuck in dense regions of the embedding space, where many visually similar images produce tightly clustered vectors. Their remedy is to raise ef. Milvus with IVF_FLAT at nprobe = 16 held perfect recall up to 10,000 vectors and slipped to 0.98 to 0.99 at 50,000 because of cluster-boundary misses. Those results came from a single workstation with four CPU cores and 4 GB of RAM per container, so absolute latencies will be lower on server hardware. The authors argue the mechanisms themselves do not depend on hardware.
Dense clusters of visually similar images arise even in a standard dataset such as CIFAR-10. That makes default HNSW settings risky for CBIR in particular. ANN-Benchmarks adds two cautions. HNSW is the least affected of the algorithms tested when pushed to high recall, but it shows the biggest slowdown going from 10-NN to 100-NN queries. On the Rand-Euclidean dataset, no HNSW setting got recall above 0.86.
ScaNN Evidence Is Thin for Images
The Faiss paper reports Faiss faster than ScaNN in batch search on Deep10M at 10-recall@10, but that comparison comes from Faiss’s own authors. A 2025 study on gene-fragment embeddings found FAISS ahead of ScaNN on indexing speed, query latency and accuracy, with ScaNN at 31% accuracy and 2.1 s search time on that task. If ScaNN is on your shortlist, test it on your own embeddings.
Tail Latency Is Yours to Measure
ANN-Benchmarks runs its experiments single-threaded on one CPU by default, for fairness. A p99 figure under production concurrency, with your batching policy, is something you have to produce yourself.
A Tuning Procedure That Holds Up
- Build exact ground truth with a Flat index, the only index that guarantees exact results.
- Measure at the k you will serve: HNSW slowed the most going from 10-NN to 100-NN in ANN-Benchmarks.
- Sweep build-time and search-time parameters together. Faiss ships a benchmarking framework that does this across accuracy, memory and search time.
- Plot the Pareto frontier of recall@k against latency, as ANN-Benchmarks does across all runs.
- Choose the cheapest configuration that meets your recall floor, then measure p99 under realistic concurrency and batch size.
- Re-run the sweep as the collection grows: in the Frontiers benchmark, Qdrant’s recall fell to 0.94 at 50,000 vectors, which its authors attribute to a sparser graph.
Index Starting Points by Situation
| Situation | Starting point | Why |
|---|---|---|
| Under about 10,000 vectors, or only a few thousand searches | Flat (exact) search | Index build time is not amortised, and non-exhaustive search matters only above roughly 10,000 vectors. |
| Ample RAM, high recall required, collection fairly stable | HNSW, tuning M and efSearch | Graph methods lead at very high recall, but builds are slow. |
| Collection changes often, rebuilds must be quick | FAISS IVF, tuning nlist and nprobe | Small, quick-to-build index that still answers queries well. |
| Memory-bound at millions of vectors or more | IVF with product quantisation | PQ compresses vectors and computes distances without decompressing them. |
| Very high query throughput | GPU IVF | By far the fastest index in ANN-Benchmarks. |
| Persistence, metadata filtering or frequent updates needed | A vector database (Milvus, Qdrant, pgvector) rather than bare FAISS | FAISS lacks persistence and native filtering, and the in-memory versus persistent choice has the biggest impact. |
Should You Use a CLIP-Class General Embedding Model or a Domain-Fine-Tuned One?
Start with a general model, measure it on your own queries, and expect to fine-tune when the task is instance-level or fine-grained. CLIP was pre-trained on 400 million image-text pairs and transfers zero-shot to many downstream tasks. Its weakness for CBIR is specific. Because CLIP learns from captions, its image encoder tends towards semantic similarity, so a photo of a burger and chips and a photo of a fast-food restaurant can land close together because both would be captioned “visiting a fast-food restaurant”. That makes it suboptimal for instance-level content-based retrieval.
On the Universal Embedding Dataset (8 domains, 1.4 million index images), a single universal model came close to per-domain specialists and beat them on two domains, using 8 times fewer parameters than the combined specialists. Every winning entry in the related challenge started from a CLIP backbone and then fine-tuned it on multi-domain data. Training details mattered too: in the second-placed solution, separate learning rates for the backbone and the projection layers raised mMP@5 from 62.1 for the pre-trained model to 70.9. “General” in that result means broadly fine-tuned, not off the shelf.
Width.ai, a vendor reporting on its own client work, says off-the-shelf CLIP matched the right product on real retail shelf images 41% of the time and 89% after domain fine-tuning. Its rule is that frozen embeddings are fine when classes are visually distinct, and fine-tuning becomes necessary for fine-grained tasks such as SKU variants or the same product across marketplaces. The figures come from the vendor’s own client projects, not an independent benchmark. A near-duplicate detection study is more measured: it generally favours fine-tuning, but at high-specificity settings the gains depend on the dataset and are often small. In pathology, the SISH encoder was trained once on TCGA slides and retrieved well on an independent hospital cohort with no fine-tuning or domain adaptation.
Fine-tuning also has running costs beyond training. Adding new categories forces a choice between repeated fine-tuning on old and new data, which is slow, and fine-tuning on new data only, which risks catastrophic forgetting. Each embedding improvement needs a full back-fill before deployment, which Pinterest described as potentially prohibitively expensive when it maintained three specialised embeddings. Pinterest’s answer was one multi-task embedding that beat all three specialists and cut experimentation, storage and serving costs.
To decide, label a few hundred real queries with their correct matches, run the off-the-shelf model through a Flat index, and look at recall@k on the queries that matter commercially. If the failures are fine-grained, such as SKU variants being confused, fine-tune. If they are vague semantic misses, a better general model or a text signal may be enough.
What Are the Trade-Offs Between Content-Based and Content-Plus-Text Retrieval (CLIP-Style)?
A shared CLIP space gives you text-to-image search, image-to-image search and zero-shot classification from one model. That convergence of vision and language is a broader shift in computer vision and NLP. The cost shows up when you optimise for image retrieval. Fine-tuning only the image encoder misaligns it with the text embeddings, so a system that needs both image-to-image and text-to-image search ends up maintaining two separate vector sets.
Two-stage fine-tuning (optimise the image encoder, then realign the text encoder) and multi-caption pairing during retrieval training both keep a single embedding per image while improving image retrieval. The text side does not always come through unchanged: after the multi-caption method, text-to-image quality rose on Flickr30k and fell slightly on MS-COCO. So the trade-off is concrete. Image-only fine-tuning gave the highest image-to-image retrieval scores in that study. Joint embeddings give one index for both query types, at the price of extra training effort to keep the two modalities aligned.
How Reverse Image Search Relates to Content-Based Image Retrieval
Reverse image search is a CBIR technique: the user submits an image and the system searches its collection for it. The two architectures share the same core of an image encoder plus an index, and they part ways in what counts as a match.
Production systems show the spread. Google’s Search by Image builds a mathematical model of the submitted picture and compares it with its databases to return matching and similar images. TinEye computes a compact fingerprint that can match heavily edited copies but usually does not return merely similar images. eBay’s ShopBot uses a ResNet-50 for category recognition, with image hashes stored in Google Bigtable. Bing combines deep neural network encoders, category, face, colour and duplicate-detection features. Its published web-scale visual search system indexes tens of billions of images and responds in under 200 ms through a cascaded learning-to-rank framework.
They diverge at the decision step. Similarity search returns the top k by distance. Copy and near-duplicate detection instead runs threshold-limited queries designed to find every near-duplicate while rejecting images that are merely similar. The 2021 Image Similarity Challenge framed this as deciding whether a query is a modified copy of any image in a 1-million-image reference set, where most queries and references are distractors. Content moderation at scale also relies on range queries, using embeddings such as SSCD on a Faiss index with human verification downstream. For that kind of system, tune the distance threshold against false positives per query rather than recall@k.
Content-based video retrieval adds time on top of the image patterns. Systems either aggregate frame features into one video-level vector, which fits a standard ANN index, or compare frame-to-frame similarities, which usually performs better but costs more. Temporal Context Aggregation narrows that gap with self-attention over frame features. Its authors report roughly 17% higher mAP on FIVR-200K than other video-level methods, and results competitive with frame-level methods at about 22 times faster inference. The image pattern breaks in two places. First, relevance becomes graded: FIVR defines associations ranging from duplicates to videos of the same incident. Second, video copy detection adds temporal localisation. The 2023 Video Similarity Challenge asks systems both to detect shared content and to locate it in time within each video. For video-text search, CLIP4Clip showed that CLIP’s image knowledge transfers to video retrieval end to end.
Where Is CBIR Used in Production: E-Commerce, Media Archives, Medical Imaging, Security?
CBIR runs in e-commerce, media archives, medical imaging and security systems.
E-commerce. Pinterest reported over 600 million visual searches a month. Its earlier work argued that a small engineering team could build and run a large-scale visual search system on AWS with open-source tools. JD.com’s visual search served 300 million daily active users and sustained 80 million database updates an hour when it was deployed in 2018. How this works in stores and online shops, from shelf recognition to shop-the-look, is the subject of our piece on how visual search and CBIR power in-store and online retail. Retrieval also feeds generation, which is the territory of visual RAG for product discovery.
Media archives and platform integrity. Faiss has been used to remove duplicates from a 1.3-billion-image dataset and for moderating harmful content against labelled examples at billion scale.
Medical imaging. SISH, a self-supervised whole-slide image search tool, was evaluated on 22,385 diagnostic slides across 13 anatomic sites and 56 disease subtypes. On merged databases of 5.5 million and 13.4 million patch images, its mean query was 120 and 230 times faster than the Yottixel baseline. Its authors point to uses such as finding morphologically similar cases for rare diseases that lack enough examples to train a classifier. In radiology, recent work proposes vision foundation models as off-the-shelf feature extractors, because CBIR systems built for specific pathologies are of limited use beyond them.
Security and fraud. One near-duplicate benchmark used a 201,961-image insurance claims dataset as a realistic fraud-detection case. Survey authors list face search and person re-identification among applications where standard benchmarks fall short of real deployments. Face matching itself is covered in the explainer linked above.
Changing the Embedding Model Means Re-Tuning the Index
The index and the model are coupled. The Frontiers authors note that newer models such as DINOv2 and SigLIP produce higher-dimensional embeddings with different geometry, which may change how HNSW and IVF indexes behave. In the Frontiers benchmark, at the same default HNSW settings, the more tightly clustered STL-10 embeddings gave lower recall than CIFAR-10 at 1,000 and 5,000 vectors (0.82 to 0.84 against 0.88). Treat each model change as an index change too: back-fill, re-run the parameter sweep and re-measure p99 before switching traffic.
Who Can Help Us Build and Tune a CBIR System?
TechnoLynx’s computer vision R&D team builds and tunes content-based retrieval for teams that need it working on their own images: choosing and fine-tuning the embedding model, setting up and tuning the ANN index, and measuring recall@k and tail latency on the real collection and hardware.
You may not need us. A team with ML engineers and a category-level search problem on a modest collection can often get far with a CLIP-class model, a Flat or HNSW index and the procedure above. A specialist is worth bringing in when the task is instance-level, the collection runs to tens of millions of images, or latency targets are tight enough that index tuning and serving design decide whether the product works.