A robot drives about 150 m: once round a 100 m loop, then half of it again. Odometry alone leaves its map 3.5 m off on average. Word scores find every revisit, but a look-alike corridor scores high too, and two false loop closures leave the map 12.4 m off. A geometric check rejects both, keeps 21 true closures, and the map ends 0.30 m off.
Pick a method. Then drag the frame slider and stop at frame 25, where a corridor looks like frame 3. Then we build it piece by piece: words, the bag, tf-idf, the score, the tree and the index, the check, time, and precision against recall.
You need Lecture 6 (ORB features and the Hamming distance), Lecture 8 (RANSAC) and a little Python. We build the rest from zero.
Lecture 12 of 14 in our follow-along of MIT 16.485, Visual Navigation for Autonomous Vehicles (VNAV, taught by Luca Carlone). Every idea is re-taught here in our own words and devices. Previous: Lecture 11, visual-inertial odometry. Next: Lecture 13, SLAM and factor graphs.
Illustrative toy world: 40 places on a 100 m loop, 60 camera frames, a 256-word vocabulary and about 39 features per frame. A corridor at places 25 and 26 copies the look of places 3 and 4. The robot matches each frame to frames at least 10 older. A match counts if its score is 0.35 or more; the check also needs 8 matches that agree on one image motion. The map is a pose graph solved in your browser.
Chapter 0
Add a true loop closure, then a false one, and watch the map heal and then fold
Odometry adds up small steps. Lecture 11 made each step good, but each step still carries a small error, and the errors add up. Nothing inside odometry can remove them, because odometry measures each step only against the one before.
In our toy, a robot drives a 100 m rectangle in 40 steps of 2.5 m. Its odometry turns 0.4° too far on every step. When it comes back to its start, the odometry puts it 4.9 m away. The map now holds two copies of the start.
The pink dashed rectangle is the true route. The purple path is the robot's map. Choose what the map is told.
Illustrative toy: 41 poses, odometry with 3 cm of noise per step and a heading bias of 0.4° (spread 0.2°) per step. Gauss-Newton solves the map over poses with position and heading (Lecture 13). The error is the root mean square distance from each mapped pose to its true pose.
Now suppose the robot recognises its start. That recognition is a loop closure: a new measurement that says "frame 40 and frame 0 show the same place". The back end of Lecture 13 moves every pose so that the odometry and the closure agree as well as they can. The 4.9 m gap spreads round the loop in small pieces. The average error falls from 2.63 m to 0.12 m.
The back end trusts the closure as much as it trusts odometry. Tell it that frame 25 is frame 3, two places 22 m apart, and it obeys. With the true closure still in place, the average error grows to 13.2 m. The false closure costs five times what the true one gained.
So place recognition has a lopsided job. Given the newest camera image and every older image, find the older image that shows the same place, or say "none". A missed revisit costs a little drift until the next one. A false one folds the map. Precision matters far more than recall.
Symptom: after a loop closure, two different streets lie on top of each other in the map.
Measure: how hard each closure pulls against the odometry after the solve. A false closure strains every odometry step near it.
Fix: check every closure geometrically (Chapter 6), demand agreement over time (Chapter 7), and use a robust back end (Lecture 14).
Chapter 1
Drop a descriptor and watch it snap to its nearest visual word
Each image gives a few hundred keypoints, each with a descriptor. Lecture 6 built ORB: a 256-bit string, compared by the Hamming distance, the number of bits that differ. Comparing every descriptor of a new image with every descriptor of every old image costs too much. With 300 features per image and 26,300 old images, that is 2.4 billion Hamming distances for one query.
Text search solved this long ago. It does not compare documents letter by letter. It looks each word up in a dictionary and compares word lists. Sivic and Zisserman (2003) did the same for images and called the dictionary a visual vocabulary.
Build it once, offline. Collect many descriptors from training images. Group them with k-means into K clusters. Each cluster centre is a visual word. At run time, replace each new descriptor by the number of its nearest centre.
Real descriptors have 256 bits; this toy has 2 numbers so we can draw it. Faint dots are training descriptors, stars are the 4 words. Tap anywhere to drop a descriptor. Press the step button to run k-means.
Illustrative: 120 seeded training descriptors in four groups around the text's four centres. One k-means step assigns every descriptor to its nearest centre, then moves each centre to the mean of its descriptors.
Write the snap as a rule. Call the new descriptor d, the K word centres c1 to cK, and the distance between two descriptors dist.
Word of d equals the k that makes the distance from d to c-k smallest.
Measure the distance from d to every centre c-k. Find the smallest. The number of that centre is the word.
The text's centres: c1 = (1, 2), c2 = (4, 1.5), c3 = (3, 5), c4 = (6.5, 4). The descriptor d = (3.8, 1.8) lies 2.81, 0.36, 3.30 and 3.48 from them. The smallest is 0.36, so d becomes word 2.
For binary descriptors the mean of a cluster is not a bit string. DBoW2 (Gálvez-López and Tardós, 2012) uses k-medians instead: each bit of a centre is the majority bit of its cluster. The vocabulary is a fixed lookup table after that. The robot never runs k-means while it drives.
Symptom: the same patch, seen twice, gets two different words.
Measure: the share of repeated features whose word changes. In our toy world, 12% of features land on a neighbouring word.
Fix: a vocabulary that is not too fine for the noise. Too few words, and different patches share a word. Too many, and one patch splits across neighbours.
Chapter 2
Count the words of two frames and see how many they share
An image is now a list of word numbers. Count how many times each word appears. The result is a bag of words: a vector of length K, one count per word. It forgets where each feature was. A word at the top left and the same word at the bottom right count the same.
Two images of one place share many words. Two images of different places share few. That is the whole idea, and it is cheap: one vector per image instead of hundreds of descriptors.
Frame 43 is the robot back at place 3. Choose an older frame. Filled dots have a word that the other frame also has. The strip below shows all 256 word counts: frame 43 up, the other frame down.
Illustrative toy frames. Grey ticks under the strip mark the 8 common words (ground texture, sky edges) that most frames contain.
Raw counts depend on how many features an image has. A sharp image with 60 features has bigger counts than a blurred one with 20. So divide each count by the total. Call the count of word i in this image ni and the number of features n.
tf-i equals n-i over n.
Count the features with word i to get n-i. Divide by the total n. The shares of all words add up to 1.
Frame 43 has n = 35 features. Word 104 appears n104 = 3 times, so tf104 = 3 / 35 = 0.086. Word 188 appears once: 1 / 35 = 0.029.
In the device, frame 43 shares 21 of its 31 words with frame 3. It shares 14 with the look-alike frame 25 and 6 with frame 17. But 5 of the 6 words shared with frame 17 are common words that nearly every frame has. Chapter 3 deals with them.
Symptom: two different places get almost the same bag.
Measure: shared words between frames that you know are far apart. Frame 25 shares 14 words with frame 43, close to the true revisit's 21.
Fix: the bag has no layout to check. Bring the positions back for the best candidates only (Chapter 6).
Chapter 3
Turn on the idf weight and watch the common words shrink
Some words appear almost everywhere: a patch of tarmac, a roof edge against the sky. In our toy, word 38 is in 38 of 40 training images. A match on it says nothing about where you are. It is the visual "the".
Text search weights each word by how rare it is. Count how many training images contain each word. A word in few images is a strong clue; a word in all of them is no clue. This weight is the inverse document frequency, or idf.
Top: frame 43's 31 words, each bar its share of the weight; grey ticks mark common words. Bottom: every older frame's score against frame 43. Toggle the idf weight.
Illustrative toy. The idf comes from 40 training images taken on an earlier drive, one per place. Scores use the L1 score of Chapter 4. Frames 1 to 5 show place 3 or its neighbours, so they count as right.
Call the number of training images N, and the number of them that contain word i Ni. Multiply each word's share by its rarity.
w-i equals n-i over n, times the natural log of N over N-i.
Find word i's share n-i over n. Divide N by N-i to see how rare the word is, and take the log. Multiply the two. A word in every image gets log 1, which is 0.
Frame 43, n = 35. Word 38 appears 3 times and sits in N38 = 38 of N = 40 training images: 0.0857 × ln(40/38) = 0.0857 × 0.051 = 0.0044. Word 188 appears once and sits in 2 of 40: 0.0286 × ln 20 = 0.0286 × 3.00 = 0.086. The rare word, seen once, outweighs the common word seen three times 19 to 1.
In frame 43, the 8 common words hold 28.6% of the raw counts and 4.3% of the tf-idf weight. Frame 3 stays first, but the best wrong frame drops from 0.448 to 0.347. The gap between right and wrong grows from 0.097 to 0.182.
This is the weighting of Sivic and Zisserman (2003). DBoW2 computes the idf once, from its training images. Video Google computed it on the film it searched. Either way, the query multiplies its shares by a stored list of weights.
Symptom: every frame scores about the same against every other frame.
Measure: the share of a frame's weight held by words with a small idf. Frame 43: 28.6% without the weight.
Fix: apply the idf, and train it on images like the ones the robot will see. A vocabulary trained outdoors finds different words common than one trained indoors.
Chapter 4
Lay two bags on top of each other and add up what they share
We need one number for how alike two weighted bags are. First scale each bag so its entries add up to 1. The sum of the sizes of a vector's entries is its L1 norm, written with single bars, so the scaled bag is v / |v|. Now both bags are shares of 1.
Call the two weighted bags v and w, with entries vi and wi. DBoW2 uses the L1 score.
s of v and w equals one minus one half of the sum over i of the size of v-i over the norm of v, minus w-i over the norm of w.
Turn both bags into shares. For each word, find the gap between its two shares. Add the gaps, halve the total, and subtract it from 1. The result equals the overlap: for each word, take the smaller of the two shares, and add them up.
With made-up shares v = (0.5, 0.3, 0.2, 0) and w = (0.4, 0, 0.4, 0.2): the gaps are 0.1, 0.3, 0.2 and 0.2, which add to 0.8. So s = 1 − 0.4 = 0.6. The overlap gives the same: 0.4 + 0 + 0.2 + 0 = 0.6.
Blue outlines are frame 43's shares, purple outlines the other frame's. The filled part of each bar is the overlap; yellow is the gap. Choose the other frame.
Illustrative toy, tf-idf weights. The device sorts words by frame 43's share and draws only words present in either frame.
Why does the overlap form matter? A word that is missing from either bag adds 0 to the overlap. So only shared words do any work. Chapter 5 uses that to skip every image that shares nothing.
Nistér and Stewénius (2006) found that this L1 form gave better retrieval than the usual L2 form, and DBoW2 adopted it. Video Google ranked by cosine similarity. On our frames the cosine gives 0.529, 0.287 and 0.053 against the L1 score's 0.529, 0.316 and 0.060: the same order.
Symptom: one threshold works in a busy street and fires all the time in a bare corridor.
Measure: a frame's score against the frame just before it. That is the best score this scene can give, and it changes from scene to scene.
Fix: divide by that score (the normalised score of Chapter 7).
Chapter 5
Walk a descriptor down the tree, then walk the query through the index
Two costs remain. Chapter 1 compares each descriptor with every centre: a million distances per feature for a million words. Chapter 4 compares the query's bag with every old bag.
Nistér and Stewénius (2006) fixed the first with a vocabulary tree. Run k-means with a small number of clusters, the branching factor b. Then run it again inside each cluster, and again, for L levels. The leaves are the words. A new descriptor walks down: at each level it compares itself with b centres and takes the nearest.
K equals b to the L, and c equals b times L.
Each level multiplies the number of nodes by b, so L levels give b multiplied by itself L times. The walk down visits L levels and checks b centres at each, so it costs b times L.
DBoW2's tree has b = 10 and L = 6: K = 106, a million words. It reaches a word in c = 60 comparisons instead of a million, about 16,700 times fewer. Our toy tree has b = 4 and L = 4: 256 words in 16 comparisons.
An inverted index, from text search, removes the second cost. For each word, keep the list of old images that contain it, with the word's weight there. A query walks only the lists of its own words. Because the score is an overlap, an image on none of those lists scores 0 and is never touched.
Tree: each step shows the 4 children of the current node; the warm one is nearest. Index: each row is one of frame 43's words, each column an older frame, and a dot means the frame is on that word's list.
Illustrative toy: a word's number written in base 4 is its path down the tree. The index holds frames 0 to 33, the frames old enough to match frame 43. "Common words" are the 5 with an idf below 0.5.
Frame 43's 31 words point to 331 list entries over 34 old frames. Skip its 5 most common words, as Video Google's stop list did, and 180 remain. Whole bags would touch 34 × 256 = 8,704 entries. At DBoW2's scale the gap is wider. Take 300 words per image, a million words and 26,300 images. A word used evenly sits on about 8 lists, so a query reads about 2,400 entries instead of 26,300 bags.
Symptom: queries slow down as the map grows.
Measure: the length of the longest lists. In our toy, common word 38 is on all 34 old frames' lists.
Fix: skip words with a tiny idf (a stop list). They add little score and most of the work.
Chapter 6
Match the shared words, run RANSAC, and see the look-alike fall apart
Frame 25 shows a corridor built like the one at frame 3. In our toy world, 20 of its 24 corridor landmarks carry the same words as frame 3's. Its best match is frame 3, with a score of 0.389, above the 0.35 threshold. The bag cannot tell these two places apart. This is perceptual aliasing: different places that look alike to the descriptor.
The layout can tell them apart. In a true revisit, the shared features sit in the same arrangement, moved by one camera motion. In the look-alike, the same words sit in different places. So bring the positions back, for the top candidate only.
Each line joins two features with the same word. Green lines agree on one image motion, red lines do not. Choose a pair, then move the number of agreeing pairs you demand.
Illustrative toy: the model is a 2D image motion (turn, scale and shift), fixed by 2 pairs, with a 5 px threshold and 300 seeded tries. Real systems fit a fundamental or essential matrix (Lectures 7 and 8). We checked every count against a search over all pairs of pairs.
The true revisit has 28 word pairs, and 16 agree on one motion. The look-alike also has 28 pairs, but only 3 agree. With 8 required, the check accepts frame 43 and rejects frame 25. An exhaustive search over every pair of pairs finds the same 16 and 3, so RANSAC missed nothing.
The check gives one more thing. The motion it fits is the relative pose between the two frames (Lecture 7). That relative pose becomes the loop-closure measurement in the pose graph.
Symptom: false closures get through the check.
Measure: the agreeing pairs of rejected look-alikes. Here 3. Demand 3 and the look-alike passes.
Fix: set the number high enough above chance. If two places are identical in 3D too, no image check can split them. Use time (Chapter 7), odometry and a robust back end (Lecture 14).
Chapter 7
Demand several frames in a row and watch the lone flukes vanish
A robot's frames come in order, and DBoW2 uses that twice. First, the raw score depends on the scene. A busy street gives high scores everywhere; a bare wall gives low ones. The frame just before the query shows nearly the same scene, so its score is about the best this scene can give. Divide by it.
Call the query frame t, its bag vt, an old candidate's bag vj, and the previous frame's bag vt−1.
Eta of t and j equals s of v-t and v-j, over s of v-t and v-t-minus-one.
Score the candidate. Score the previous frame. Divide the first by the second. DBoW2 skips queries whose previous-frame score is tiny, for example while the robot turns.
Frame 43 against frame 3 scores 0.529; against frame 42 it scores 0.276. So η = 0.529 / 0.276 = 1.91. Frame 25 against frame 3 scores 0.389, and against frame 24 0.481, so η = 0.81.
Be honest about our toy: here η does not separate better than s. At 100% precision, a threshold on s finds 19 of the 22 revisits, and a threshold on η 18. Its job is to let one threshold work across scenes that differ more than ours do.
Second, a true revisit lasts. If frame t matches frame j, frame t+1 should match a frame near j. DBoW2 accepts a match only when it agrees with the k queries before it, with k = 3. This is temporal consistency.
Each bar is one query frame's best score. Frames 38 to 59 have a true revisit. A dot above a bar means it fires: green if right, red if wrong. Change the frames in a row you demand, and the threshold.
Illustrative toy, tf-idf scores, no geometric check. "Agrees" means the matched old frame is within 2 of the previous query's match.
At a threshold of 0.25, single frames fire 4 false closures: frames 24, 25, 26 and 33. Demand 3 in a row and only frame 26 remains. Frame 33 was a lone fluke. The look-alike corridor lasts three frames, so time alone cannot stop it. The cost is delay: the first true closure comes at frame 40 instead of 38.
Symptom: loop closures arrive late, or not at all on short revisits.
Measure: the frames between the first true match and the first accepted closure. With 3 in a row: 2 frames.
Fix: pick k from the frame rate. DBoW2 found a big gain from k = 0 to any k above 0, and chose 3.
Chapter 8
Slide the threshold and watch three detectors trade false alarms for missed revisits
Every query ends one of four ways. It fires on the right place: a true positive. It fires on the wrong place: a false positive. It stays silent though a revisit exists: a false negative. Or it stays silent with nothing to find. Over our 50 queries, 22 have a true revisit.
Call the counts TP, FP and FN. Two numbers sum them up.
P equals TP over TP plus FP.
Count the closures that fired. Divide the right ones, TP, by all of them, TP plus FP.
tf-idf at a threshold of 0.35: TP = 21 and FP = 2, so P = 21 / 23 = 0.913.
R equals TP over TP plus FN.
Count the true revisits, TP plus FN. Divide the ones that fired, TP, by that count.
The same run: TP = 21 and FN = 1, so R = 21 / 22 = 0.955.
Each curve is one detector as the threshold sweeps from high (left) to low (right). The dots mark the threshold on the slider. SLAM wants the top edge: precision 1.
Illustrative toy: 50 queries, best candidate only, one detection per query, no temporal check. The check demands 8 agreeing pairs.
At 0.35, raw counts fire 7 false closures, tf-idf 2 (both on the look-alike), and tf-idf with the check none. Raise the threshold to 0.45 and tf-idf alone reaches precision 1, but recall drops to 18 of 22. The check lets a low threshold keep every revisit and still fire no false closure.
Read a place-recognition paper's curve at its top edge: the recall at 100% precision. DBoW2 tuned its normalised-score threshold this way on each dataset.
Symptom: the map is good on the test drive and folds on a new one.
Measure: precision on a drive the threshold never saw.
Fix: keep a margin above the tuned threshold, and never let the score alone decide: the check and time catch what the threshold misses.
Chapter 9
Play the drive, set every knob, and watch the map hold or fold
Here is the whole detector on the whole drive. At each frame the robot builds the bag, scores every frame at least 10 older, takes the best, and applies the checks you switch on. Every closure it accepts goes into the pose graph, and the back end solves the map again.
Press play. Try word counts with no check, then tf-idf, then the check. Drop the threshold to 0.2 and see what the check still saves. Demand 3 in a row and see the delay.
Illustrative toy: the same world, frames and pose graph as the hero. The check demands 8 agreeing pairs. A true closure gives the pose graph the true relative pose; a false one claims the two frames stand at the same pose.
Three things to see. With word counts and no check, the common words make many frames look alike, and 7 false closures fold the map. With tf-idf, only the look-alike corridor gets through, but it is enough. With the check, every false closure is gone, and the 21 true ones pull the map to 0.30 m.
Now set the threshold to 0.2 with the check on. Word scores alone would fire on almost every frame. The check still rejects every wrong one, because chance gives 2 or 3 agreeing pairs and the check asks for 8. That is why real systems keep the score loose and the check strict.
Chapter 10
Keep the formulas, the numbers and the code side by side
Odometry drifts, and only recognising a place closes the loop. Turn each descriptor into its nearest visual word, count the words, weight them by rarity, and score bags by their overlap. A vocabulary tree finds words fast and an inverted index touches only images that share them. Then check the layout with RANSAC and demand agreement over time, because one false closure folds the map.
| Piece | Formula | Number on this page | Watch out |
|---|---|---|---|
| Loop closure | pose graph edge | 2.63 m to 0.12 m; one false: 13.2 m | precision first |
| Word | argmink dist(d, ck) | (3.8, 1.8) to word 2 at 0.36 | Hamming for ORB |
| Term frequency | ni / n | 3 / 35 = 0.086 | layout is gone |
| tf-idf | (ni / n) ln(N / Ni) | common words 28.6% to 4.3% | train on similar places |
| L1 score | 1 − ½ Σ |vi/|v| − wi/|w|| | 0.529 true, 0.389 look-alike | not a probability |
| Tree | K = bL, c = bL | 106 words in 60 steps | log in words, not images |
| Inverted index | lists of shared words | 331 entries, 180 with a stop list | long common lists |
| Check | RANSAC inliers ≥ m | 16 of 28 true, 3 of 28 look-alike | 3D twins pass |
| Normalised score | η = s(vt, vj) / s(vt, vt−1) | 1.91 true, 0.81 look-alike | skip turning frames |
| Precision, recall | TP/(TP+FP), TP/(TP+FN) | 0.913, 0.955 at 0.35 | read the top edge |
python import numpy as np, cv2 from collections import defaultdict idf = np.log(N_train / np.maximum(N_i, 1)) # once, from training images def bag(words, K): # words: one id per feature tf = np.bincount(words, minlength=K) / len(words) w = tf * idf return w / w.sum() # shares of 1 index = defaultdict(list) # word -> [(frame, share)] def add(frame, v): for i in np.nonzero(v)[0]: index[i].append((frame, v[i])) def query(v, now, gap=10): score = defaultdict(float) for i in np.nonzero(v)[0]: # only the query's own words for f, share in index[i]: if f <= now - gap: score[f] += min(v[i], share) # overlap = L1 score return max(score.items(), key=lambda x: x[1], default=(None, 0.0)) # the check: p1, p2 are (N, 2) pixels of features paired by word F, mask = cv2.findFundamentalMat(p1, p2, cv2.FM_RANSAC, 1.0, 0.99) accept = mask is not None and int(mask.sum()) >= 12 # DBoW2's demand
We ran this query on our toy frames. Its overlap sum equals the L1 score to machine precision. It picks the same best frame as the full comparison on all 50 queries.
Bags of words are fast, need no GPU, and come with features that the check can use. Their weak spot is a change of look: day against night, summer against snow. The descriptors change, so the words change. Two other lines of work attack this.
A learned global vector finds candidates. The check still decides, because the back end needs a verified relative pose.
Lecture 6 gave the ORB features, Lecture 8 the check, and Lecture 11 the drifting odometry. Lecture 13 turns each verified closure into an edge of the factor graph. Lecture 14 makes the back end survive the false closure that gets through anyway.
Now press Present or Teach. Explain why one false closure is worse than many missed ones. Work the tf-idf weight of a common and a rare word, and show that the L1 score is an overlap. Say why the inverted index only touches images that share a word. Then go back to the hero and say why frame 25 fools tf-idf but not the check.