Search

Search papers and lessons

Bag of Visual Words

Level 3 · 10 min read

Bag of visual words turns an image's local features into a histogram of counts over a learned vocabulary, so whole images can be compared and searched like documents.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Linear algebra
  • Architectures
  • Learning basics
  • Computer vision
  • Sign in to see your progress

TL;DR

A bag of visual words describes a whole image as a histogram. First, a large set of local feature descriptors from many images is clustered into a vocabulary of visual words. Then each image is reduced to counts of how often each word appears, ignoring where in the image they appeared. Two images can now be compared by comparing two short count vectors, and a large collection can be searched with an index built on those words.

This is the same trick a search engine uses for text, with image patches in place of words.

Where you'll see it: place recognition and loop closing in visual SLAM (a robot recognising a room it has already visited), image retrieval in photo collections, and fast candidate lookup before a more expensive geometric check.

Intuition

Think about how you would tell that two documents are about the same topic without reading them closely. You would count the words, ignore the order, and notice that both use "volcano", "lava" and "eruption" often. The word order is lost, but the counts are enough for a good first guess.

Images have no words, but they have local features: a few hundred small, distinctive patches, each described by a vector (see Local Image Features). Those vectors play the role of words, with one difference. Two patches that show the same corner of a building give nearly equal vectors, but they are never exactly equal, so you cannot just count identical vectors. The fix is to group similar descriptors into clusters and call each cluster a word. Clustering is done with K-Means Clustering on descriptors gathered from many training images. The cluster centres form the vocabulary, and a new descriptor is given the word of its nearest centre. That step is the Vector Quantization idea: snap a continuous vector to a discrete code.

The payoff is that an image of thousands of descriptors becomes one fixed-length vector with one entry per word. Comparing two images no longer means matching every patch against every other patch. It means comparing two histograms, which is cheap, and it means the robot does not need to know where in the image the features were, only which kinds of features it saw.

flowchart LR
  A[Training descriptors from many images] --> B[k-means clustering]
  B --> C[Vocabulary of k visual words]
  D[New image descriptors] --> E[Assign each to nearest word]
  C --> E
  E --> F[Word histogram for the image]
  F --> G[Compare or index histograms]

The math

Let the vocabulary be {w1,…,wk}\{\mathbf{w}_1, \dots, \mathbf{w}_k\}, a set of kk cluster centres in descriptor space. For an image II with local descriptors d1,…,dn\mathbf{d}_1, \dots, \mathbf{d}_n, the raw count of word jj is

cj(I)=∑i=1n1[ j=arg⁡min⁡l∥di−wl∥ ],c_j(I) = \sum_{i=1}^{n} \mathbf{1}\left[\, j = \arg\min_{l} \lVert \mathbf{d}_i - \mathbf{w}_l \rVert \,\right],

where 1[⋅]\mathbf{1}[\cdot] is 1 when the condition holds and 0 otherwise. The image is represented by the vector c(I)=(c1(I),…,ck(I))\mathbf{c}(I) = (c_1(I), \dots, c_k(I)). Each descriptor contributes exactly one count, to its nearest word.

Raw counts favour images with many features, so the vector is normalised. The most common choice is to divide by the total, so the entries sum to 1:

vj(I)=cj(I)∑lcl(I).v_j(I) = \frac{c_j(I)}{\sum_{l} c_l(I)}.

Some words are everywhere (a generic edge, say) and tell you little. A standard fix, borrowed from text retrieval, is inverse document frequency. If NN is the number of images in the database and NjN_j the number of images that contain word jj, then

idfj=ln⁡NNj.\mathrm{idf}_j = \ln\frac{N}{N_j}.

A word in every image gets weight ln⁡1=0\ln 1 = 0. A rare word gets a large weight. Combining the two gives the tf-idf weight

tj(I)=vj(I)⋅idfj,t_j(I) = v_j(I) \cdot \mathrm{idf}_j,

and the image is represented by the vector t(I)=(t1(I),…,tk(I))\mathbf{t}(I) = (t_1(I), \dots, t_k(I)), which is rescaled so its entries sum to 1 before comparison.

Two images are compared with a similarity score. A common choice for vectors whose entries sum to 1 is the L1 distance between them, converted to a score in [0,1][0, 1] with

s(I,J)=1−12∑j=1k∣tj(I)−tj(J)∣,s(I, J) = 1 - \tfrac{1}{2} \sum_{j=1}^{k} \lvert t_j(I) - t_j(J) \rvert,

where a score of 1 means identical histograms and 0 means completely disjoint ones.

Why the vocabulary is learned once

Clustering is the expensive step, so the vocabulary is built offline from a training set and then frozen. A new image only needs nearest-word lookups and a histogram. This is also why the vocabulary size matters: a larger kk separates appearances more finely, but each lookup and each histogram is larger, and a word seen rarely in training may not be learned well.

Worked examples

Example 1: a three-word vocabulary

Take a toy vocabulary with k=3k = 3 words, and a database of N=1000N = 1000 images.

Example
Histograms and similarity by hand
  1. Image A has six descriptors, assigned to words 1,1,2,3,3,31, 1, 2, 3, 3, 3. Counts: c(A)=(2,1,3)c(A) = (2, 1, 3).
  2. Image B has four descriptors, assigned to words 1,2,2,21, 2, 2, 2. Counts: c(B)=(1,3,0)c(B) = (1, 3, 0).
  3. Normalise to sum to 1. v(A)=(2/6,1/6,3/6)=(1/3,1/6,1/2)v(A) = (2/6, 1/6, 3/6) = (1/3, 1/6, 1/2) and v(B)=(1/4,3/4,0)v(B) = (1/4, 3/4, 0).
  4. Suppose word 1 appears in 10 of the 1000 images, word 2 in 500, and word 3 in all 1000. Then idf1=ln⁡100≈4.605\mathrm{idf}_1 = \ln 100 \approx 4.605, idf2=ln⁡2≈0.693\mathrm{idf}_2 = \ln 2 \approx 0.693, idf3=ln⁡1=0\mathrm{idf}_3 = \ln 1 = 0.
  5. Weight: t(A)=(13⋅4.605, 16⋅0.693, 0)≈(1.535,0.116,0)t(A) = (\tfrac{1}{3} \cdot 4.605,\ \tfrac{1}{6} \cdot 0.693,\ 0) \approx (1.535, 0.116, 0). Word 3 drops out because it is in every image.
  6. Weighted vector for B: t(B)=(14⋅4.605, 34⋅0.693, 0)≈(1.151,0.520,0)t(B) = (\tfrac{1}{4} \cdot 4.605,\ \tfrac{3}{4} \cdot 0.693,\ 0) \approx (1.151, 0.520, 0).
  7. Rescale each to sum to 1. A: the sum is 1.535+0.116=1.6511.535 + 0.116 = 1.651, giving (0.930,0.070,0)(0.930, 0.070, 0). B: the sum is 1.151+0.520=1.6711.151 + 0.520 = 1.671, giving (0.689,0.311,0)(0.689, 0.311, 0).
  8. L1 distance: ∣0.930−0.689∣+∣0.070−0.311∣+0≈0.241+0.241=0.482\lvert 0.930 - 0.689 \rvert + \lvert 0.070 - 0.311 \rvert + 0 \approx 0.241 + 0.241 = 0.482.
  9. Score: s=1−12⋅0.482≈0.76s = 1 - \tfrac{1}{2} \cdot 0.482 \approx 0.76.

Interpretation: both images contain the rare word 1, which idf weights heavily, so they score as fairly similar even though B also uses word 2 much more. Word 3 contributes nothing because it is in every image, which is the point of the idf term.

Example 2: how a real system uses it

Example
Loop closing in a visual SLAM system

ORB-SLAM, which uses ORB descriptors matched as in Feature Matching, builds its place recogniser on a bag-of-words vocabulary in the DBoW2 style. A vocabulary tree with branching factor 10 and depth 6 has up to 10610^6 leaves, so a descriptor is assigned to a word by walking 6 levels down the tree, comparing against 10 children at each level. That is 60 comparisons instead of a million.

  1. The robot extracts about 1000 ORB descriptors from the current frame.
  2. Each descriptor is walked down the tree to a word, giving a sparse weighted histogram over a million possible words.
  3. An inverted index maps each word to the earlier keyframes that contained it. Only keyframes that share at least one word with the current frame are scored, which avoids a comparison with every stored frame.
  4. The best-scoring keyframes become loop-closure candidates. A candidate is accepted only after geometric verification, because a histogram match alone can be wrong.

The important design point is that the histogram is a filter, not a verdict. It narrows thousands of keyframes to a handful, and the expensive geometric check runs only on those.

Tradeoffs and failure modes

SituationProblemBetter choice
Vocabulary learned on one kind of scene, used on anotherWords for new appearances are missing or coarse, so distinct places look alikeRetrain or adapt the vocabulary on data close to the deployment setting
Very small vocabularyMany unrelated patches share a word, so histograms blur togetherIncrease kk, or use a tree to keep lookups fast
Very large vocabularyMost words are seen rarely in training and are noisy; memory growsUse a hierarchical tree and idf weighting
Repeated structures (tiles, windows, fences)The same words appear in many places, so the histogram cannot tell places apartAdd geometric verification and temporal consistency checks
Need precise camera poseHistograms ignore where features are, so they give no positionUse the histogram only to find candidates, then estimate geometry from matched features
Huge databaseScoring every image is slow even with histogramsUse an inverted index, or Approximate Nearest Neighbor Search over dense global descriptors

The main failure mode is false positives from repeated structure. Two different corridors with identical tiles can share most of their words. This is why every practical system checks the geometry of a candidate before trusting it.

Bag of words is also not the only option. Learned global descriptors from neural networks often recognise places better, at the cost of training data and compute. Bag of words is still attractive because it is cheap, needs no labels, and its behaviour is easy to inspect.

History

The idea of representing a document as a bag of words is old and comes from text retrieval, where tf-idf weighting was developed in the 1970s. Computer vision adopted it in the early 2000s. Josef Sivic and Andrew Zisserman's "Video Google" work in 2003 treated video frames as documents built from quantised local features, and made fast retrieval over video possible. Gabriella Csurka and colleagues in 2004 used the name "bags of keypoints" for classification, which is where much of the vocabulary-learning recipe came into common use.

In robot mapping, the approach was adopted for place recognition, where a robot needs to say "I have been here before" from a camera stream. Dorian Gálvez-López and Juan Tardós developed the DBoW family of vocabulary trees in the early 2010s, and ORB-SLAM used this style of recogniser for loop closing. It caught on because it was fast enough for real time on modest hardware and needed no labelled data.

Check yourself

QuestionRecall: what does the word 'visual' refer to in a visual word, and where do the words come from?Show answer

A visual word is a cluster centre of local image descriptors, such as ORB or SIFT vectors, learned by clustering descriptors gathered from many training images. It is not a human-readable label. Each cluster is a recurring kind of local appearance, such as a particular corner or edge pattern.

QuestionComputation: an image has descriptors assigned to words with counts c=(4,0,6)c = (4, 0, 6). What is its normalised histogram vv?Show answer

The total is 4+0+6=104 + 0 + 6 = 10, so v=(0.4,0,0.6)v = (0.4, 0, 0.6). The entries sum to 1, so the image length no longer matters when comparing it with a larger or smaller image.

QuestionWhy does inverse document frequency give a word that appears in every image a weight of zero?Show answer

Because idfj=ln⁡(N/Nj)\mathrm{idf}_j = \ln(N / N_j), and if every image contains the word then Nj=NN_j = N. The ratio is 1, and ln⁡1=0\ln 1 = 0. The word cannot help tell images apart, so its weight is removed. A word that appears in only a few images has a large ratio and a large weight.

QuestionApplied: a robot's place recogniser returns a candidate that has a high histogram score, but the candidate is a different corridor with identical tiles. What went wrong, and how is it fixed?Show answer

The corridor's repeated tiles produce the same visual words as the true place, so the histograms match even though the places differ. The histogram only records which kinds of features appear, not where they are. The fix is geometric verification: match the actual feature positions between the two frames and check that they agree with a consistent camera motion, for example with RANSAC. A candidate that fails the check is rejected, even if its histogram score was high.

Sources