One wrong match, weighted like a good loop closure, bends the map by 7.6 m. It leaves only 1.7 mm of residual on itself, so the optimizer reports success. The frontend is the only part of SLAM that can refuse it.
Pick which earlier pose the false closure claims, and watch the map fold while every check passes. Then switch on the gate. Then we build, stage by stage, how a frontend finds points, matches them, and decides which matches to throw away.
You need a dot product, the idea of least squares and a little Python. We build the rest from zero.
Lesson 6 of the Robotics Engineering track. Before: Lesson 5, Calibration. Next: Lesson 7, The SLAM Backend. Lesson 5 made the numbers that tie the sensors together. This lesson turns sensor data into constraints, and decides which constraints to trust.
Illustrative pose graph, positions only, solved exactly by least squares: 60 poses 0.54 m apart, pose 0 fixed. Odometry links have σ = 1 cm; the closure has σ = 1 mm, so it weighs 100 links. The robot is truly back at pose 0. The gate is a 95% circle of 2.45 σ around the odometry prediction, with an illustrative drift σ of 0.4 m.
Chapter 0
Price a false constraint as a spring, and see why the optimizer cannot find it
A warehouse robot drives one lap of an aisle loop. The optimizer converges, and every residual is under two millimetres. The map still runs through a shelf. The cause is one wrong match. The camera saw an upright in aisle 11, and the software matched it to the identical upright in aisle 3.
The frontend is everything before the optimizer. It turns pixels and LiDAR returns into constraints, and it decides which measurement belongs to which landmark. That decision is data association. The backend (Lesson 7) finds the poses that best fit the constraints. It never sees an image, so it cannot tell a wrong constraint from a right one.
Why does one wrong constraint win? Treat each constraint as a spring. Odometry links are weak springs in series, and n links of stiffness 1 make a chain of stiffness 1/n. Call that chain stiffness k. A visual loop closure with hundreds of inliers is a stiff spring; call its weight Ω (omega). Call the share of the lie that the map absorbs f:
f equals omega divided by omega plus k.
The two springs pull the same pose in two directions. The pose settles at the weighted average, so the loop's share of the pull is omega over the total. The residual left on the false edge is the lie times k over omega plus k.
With made-up numbers: n = 54 links, so k = 1/54 = 0.0185. Odometry has σ = 1 cm per link and the closure has σ = 1 mm, so Ω = (1/0.001²) / (1/0.01²) = 100. Then f = 100 / 100.0185 = 0.99981. A 3.0 m lie moves the map 2.9994 m and leaves 0.56 mm on the false edge.
That 0.56 mm is 0.56 σ of the closure's own noise. A Huber kernel starts to down-weight at 1.345 σ, so it never wakes. The lie hid itself by winning.
The bar is the 3.0 m lie. Purple is how far the map moves to obey it; yellow is the residual left on the false edge. Lengthen the chain, then raise the weight.
Illustrative 1-D chain, checked against a 55-pose least-squares solve in NumPy. The closure’s σ is 10 mm / √Ω: Ω = 100 means 1 mm.
Every frontend stage compresses, and every compression is a decision. A 1280 by 720 camera at 30 Hz sends 27.6 MB/s. The backend receives about 200 bytes per frame:
Symptom: the map passes through a wall, the solver reports convergence, and every final residual is tiny.
Measure: each closure's residual before optimization, from the odometry prediction: 7.6 m against a σ of 1 mm.
Fix: reject the closure in the frontend, with the checks in Chapter 8. After optimization, the evidence is gone.
Chapter 1
Run the FAST corner test by hand, then measure whether the corners are spread out
A keypoint is a pixel the detector can find again in the next frame, from a new viewpoint. An edge fails this: slide along it and nothing changes. VNAV Lecture 6 derives the Harris test; here we run the detector that real-time frontends use.
FAST (Rosten and Drummond, ECCV 2006) looks at the 16 pixels on a circle of radius 3 around pixel p. Pixel p is a corner if at least 9 neighbouring ring pixels are all brighter than Ip + t. An arc all darker than Ip − t also counts. Ip is the centre’s brightness; t is the contrast threshold.
Why 9? A straight edge through p splits the ring 8 and 8. Nine is the smallest arc that rejects every edge. A 90° corner darkens 4 ring pixels and leaves a bright arc of 12.
By hand: Ip = 100, t = 20, ring = 64, 58, 71, 128, 139, 147, 155, 151, 144, 136, 141, 149, 133, 76, 62, 69. Pixels 4 to 13 exceed 120: an arc of 10, so p is a corner. Its score, the sum of |I − Ip| over the arc minus t, is 423 − 20 = 403. At t = 40 the longest arc is 4, so p is not a corner.
A dark wedge on a bright patch, apex at p. Blue marks ring pixels past the threshold; purple is the longest run. Open past 180°, then raise t.
Illustrative wedge, noise-free. The bright side sits at Ip + c/2 and the dark side at Ip − c/2, so the test needs c > 2t.
A detector gives where; a descriptor says what. ORB (Rublee et al., ICCV 2011) stores 256 bits per keypoint, each a brightness comparison of two pixels. The Hamming distance between two descriptors is XOR, then count the ones: 10110110 against 10010010 gives 2.
Corners must also be spread out. Bin the keypoints into an 8 by 6 grid of 48 cells, and call the share in cell k pk. The spread is the entropy H:
H equals minus the sum over k of p-k times log base two of p-k.
Multiply each share p-k by its log base two, add them up, and flip the sign. Many equal cells give a large H; a few crowded cells give a small one.
With made-up numbers: all 1000 keypoints in 4 cells, so p-k = 1/4 four times. H = −4 × 0.25 × log₂(0.25) = 2.0 bits: 0.36 of the largest value.
Symptom: in one aisle the heading drifts 3° over 20 m, always the same way. Inliers sit at 85%.
Measure: H / 5.585. Here it is 0.36: every keypoint sits on one bank of labels, so a small yaw and a sideways slide look alike.
Fix: cap keypoints per cell, and re-run FAST with a lower t in empty cells. ORB-SLAM2 uses cells of about 30 px and drops t from 20 to 7.
Chapter 2
Compare the best match with the second best, and check that the match points both ways
Every descriptor in frame A has a nearest neighbour in frame B, even when its true partner left the view. Nearest-neighbour search cannot say “none”. Matching is the craft of adding that answer.
A fixed distance threshold fails, because blur and contrast change every distance. Lowe's fix (IJCV 2004) compares two numbers from the same row. Call the distance to the nearest neighbour d₁, to the second nearest d₂, and the cut-off τ (tau):
r equals d-one over d-two; accept the match if r is less than tau.
Divide the best distance d-one by the second best d-two. Blur inflates both, so the ratio r stays put. Keep the match only if r is below tau.
With made-up Hamming distances out of 256 bits: a blurred corner has d-one = 110 and d-two = 180, so r = 0.611 and we keep it. A logo printed twice has d-one = 31 and d-two = 34, so r = 0.912 and we reject it. The far match passes and the near one fails, which no fixed distance can do.
Lowe measured the ratio for correct and false matches. At τ = 0.8 the test removed 90% of false matches and less than 5% of correct ones. Precision also depends on the overlap: the share of features whose partner is still in view.
Across: the ratio r. Blue: r when the true partner is present. Red: when it is absent. The test keeps everything left of the yellow line. Drop the overlap to 0.2, as on a fast turn.
Illustrative curves, Beta(2.4, 2.8) and Beta(13, 1.4). At τ = 0.8 they keep 95.1% of true matches and 10.2% of false ones, close to Lowe’s reported figures.
At overlap 0.6 and τ = 0.8, precision is 0.933. At overlap 0.2 it falls to 0.700 while recall stays at 0.951. The best τ by F1 moves from 0.78 to 0.70. A constant τ is a choice about your scene.
The ratio test reads one row of the distance matrix. It misses many-to-one collapse: one reflection in B can be the nearest neighbour of a dozen features in A. The mutual check reads the column too: keep (a, b) only if b's own nearest neighbour is a. In the lab, raw matching keeps 150 with precision 0.613. The ratio test gives 0.843, and both tests give 0.977, for one point of recall (0.86 to 0.85).
Symptom: after someone raised τ to 0.95 to “get the matches back”, the trajectory jumps a few times per run.
Measure: precision on a labelled bag. On the curves above it falls from 0.933 to 0.688 at overlap 0.6.
Fix: put τ back, and fix the cause of the missing matches upstream (detection, overlap). A lost match costs a little; a wrong one can fold the map.
Chapter 3
Use the motion you already predicted to shrink a million comparisons to two thousand
Brute-force matching compares every pair: 1000 by 1000 is a million Hamming distances per frame. A tracking frontend does not do this. It already predicts the new pose from the last velocity or the IMU. So it projects each map point into the image and searches only a small window around the prediction. We call this guided matching.
How big is the window? Propagate the pose uncertainty into the image to get the predicted pixel spread σu, and use a radius of 3σu. With 1000 keypoints spread over 1280 by 720 pixels, a 25 px window holds on average 1000 × π × 25² / 921,600 = 2.13 keypoints. A million comparisons become about 2,130.
The window also tames the combinatorics. Give each of M measurements a choice of N landmarks or “none”:
hypotheses = (N + 1)M: M = 5, N = 20 gives 215 = 4,084,101; a gate leaving 2 candidates each gives 35 = 243.
The gate is the chi-square test of Lesson 3: keep a landmark only if its Mahalanobis distance to the measurement is inside the 95% bound. It cut the search by 16,807 times, using a prediction we had anyway.
Blue dots are the frame's keypoints. The yellow circle is the search window, radius 3σu, around the predicted projection. Widen it, as after a dropped frame.
Illustrative frame: 1000 seeded keypoints, uniform over 1280 by 720. The expected count uses the area formula; the dots are one draw. Hypotheses assume 5 measurements, each with the expected number of candidates.
A gate tests each measurement alone. Two matches can each pass and still put the robot in two places at once. Joint compatibility (JCBB, Neira and Tardós, 2001) tests the set together with one stacked chi-square test.
The prediction is only as good as its time stamp. A stamp 20 ms stale during a 0.5 rad/s turn moves every prediction by 500 × 0.5 × 0.02 = 5 px at f = 500 px. Lesson 2 builds the clocks.
Symptom: entering one aisle, matches fall from 420 to 80 per frame while the feature count stays at 1000.
Measure: the ratio-test rejection rate: 30% in a normal aisle, 85% here. Identical uprights every 1.2 m give two equal candidates, and the test refuses to guess. (If features fell to about 120, detection failed instead.)
Fix: keep τ. Lean on a tight gate from the predicted pose, and accept fewer but correct matches until distinct structure returns.
Chapter 4
Derive how many random samples it takes to draw one clean one, and what a clean sample still cannot promise
After matching, perhaps 40% of the matches are still wrong. RANSAC (Fischler and Bolles, 1981) ignores single matches and looks for agreement. Draw the fewest matches that fix a model, fit it, and count how many other matches agree within a threshold. Repeat, and keep the largest group. VNAV Lecture 8 covers its variants.
How many draws? Call the share of correct matches w, the matches per sample s, and the confidence we want p. One sample is clean with probability ws. All N samples are dirty with probability (1 − ws)N, and we want that at most 1 − p. Take logs, and the inequality flips because both logs are negative:
N equals the natural log of one minus p, divided by the natural log of one minus w to the s.
Raise w to the power s to get the chance of one clean sample. Divide the log of the allowed failure, 1 minus p, by the log of 1 minus that chance. The result is how many samples to draw.
A line through 60% garbage: w = 0.4, s = 2, p = 0.99. w-to-the-s = 0.16, so N = ln(0.01) / ln(0.84) = −4.605 / −0.1744 = 26.4: draw 27 samples. The essential matrix at w = 0.5 with p = 0.999 needs ln(0.001) / ln(0.96875) = 218.
N against w on a log scale, one curve per sample size; yours is purple. Drag w left, then try s = 8.
Exact formula. The cost line assumes an illustrative 10 µs per five-point solve and 5 ns per residual on 400 matches.
Read a row of the curves: the essential matrix at w = 0.7 needs 26 samples, at w = 0.4 it needs 448, 17 times more. So matching quality is a runtime feature.
The threshold matters too. A squared residual over σ² is chi-square. For a point-to-line distance (1 degree of freedom) the 95% bound is √3.841 = 1.96 σ. For a 2-D reprojection it is √5.991 = 2.45 σ. Set t = 1 σ instead of 1.96 and you keep 68% of true inliers. Then w falls from 0.5 to 0.34, and N rises from 146 to 991.
We never know w in advance. Adaptive RANSAC starts with N infinite and recomputes N from the best inlier count so far. RANSAC returns a partition; refit the model on all inliers.
Symptom: facing a flat shelf, RANSAC reports 85% inliers at 0.4 px, and the translation direction flips from frame to frame.
Measure: fit a homography to the same matches and compare scores. ORB-SLAM's initializer computes RH = SH / (SH + SF) and picks the homography when RH > 0.45.
Fix: on a plane, many motions fit equally well, so do not trust the essential matrix. Decompose the homography, use another sensor, or skip the frame.
Chapter 5
Skip descriptors and align brightness, then see what one exposure step does to it
A blank wall gives FAST forty corners and discards almost a million pixels. A direct method keeps them. It assumes brightness constancy: one surface point has the same intensity in both images. Warp each pixel by the guessed motion, look up the intensity there, and subtract. That difference is the photometric residual.
Take the simplest case: a 1-D shift δ (delta). At pixel i, call the image slope gi and the current intensity error ei. Linearize, ei + giδ, and minimize the sum of squares. That gives one Lucas–Kanade step:
delta equals minus the sum over i of g-i times e-i, divided by the sum over i of g-i squared.
Each pixel votes for a shift of minus e-i over g-i. Weight each vote by g-i squared, so steep pixels count most, and average. Flat images give a tiny bottom sum and a wild step.
With made-up numbers: g = (10, −6) and e = (−4, 3). The top sum is 10 × −4 + −6 × 3 = −58. The bottom sum is 100 + 36 = 136. So δ = 58 / 136 = 0.43 px.
In 2-D the bottom sum becomes the 2 by 2 sum of g gT, the matrix the Harris detector tests. A feature method keeps the pixels where it is well conditioned; a direct method keeps them all.
The linearization holds only for shifts of a few pixels. A turn moves every pixel by fω, whatever the depth: 8.3 px per frame at f = 500 px, 0.5 rad/s and 30 Hz. So direct trackers use a pyramid (4 levels at scale 2 widen the basin 8 times) and an IMU prior (VNAV Lecture 11).
Blue is the template; the second line is the new frame, shifted and brightened. Bottom: where each tracker lands against the pink truth. Push the gain to 1.30.
Illustrative 160-pixel profile, Gauss–Newton from zero, solved live. This smooth profile has a wide basin (35 px plain, 20 px affine); real texture gives a few pixels.
Auto-exposure breaks the assumption. A 20% gain step turns 120 into 144, an error of 24 levels. At a slope of 10 per pixel, that looks like a 2.4 px shift. Model it: r = I₂(warp) − (a I₁ + b). With a = 1.2 and b = 0 the residual is zero again. DSO (Engel et al., TPAMI 2018) carries such gain and offset terms and calibrates vignette and response.
Symptom: a direct VO jumps 8 to 15 cm in one frame, two or three times a run, always near the dock door.
Measure: plot pose jumps against the change in mean intensity and against gyro rate. Exposure steps follow intensity and last one frame; blur follows gyro rate.
Fix: model gain and offset per frame, or hand that stretch to a feature tracker.
Chapter 6
Align two scans by alternating matches and a closed-form fit, and find where that stops working
Two LiDAR scans, 0.1 s apart, have no descriptors at all. To match points we need the motion, and to find the motion we need matches. ICP, iterative closest point (Besl and McKay, 1992), alternates. Match each source point to its nearest target point, solve for the best rigid motion, and repeat. AA 274A Lecture 7 introduces it.
The solve has a closed form. The best translation always moves the source centroid onto the target centroid: t = q̄ − R p̄. Centre both clouds, and call the centred points ai (source) and bi (target). In 2-D the best angle θ comes from two sums:
theta equals atan-two of the sum of a-i cross b-i, and the sum of a-i dot b-i.
Centre both clouds. Add up the cross products and the dot products of the pairs. The angle of that sum is theta. Then move the source centroid onto the target centroid to get t.
Source (0, 0), (2, 0), (1, 3); target the same points turned by 36.87° and moved by (2, −1): (2, −1), (3.6, 0.2), (1.0, 2.0). Centred, the cross products are 1.2, 1.2, 2.4 (sum 4.8). The dot products are 1.6, 1.6, 3.2 (sum 6.4). So θ = atan2(4.8, 6.4) = 36.87°, and t = (2.2, 0.4) − R(1, 1) = (2, −1), both exact.
Blue is the target scan plus clutter. Purple is the source under the current guess; warm lines are matches, red ones rejected. Run from 30°, then from 70°.
The Code Lab’s scene and kernel: 180 points on a notched room, 24 clutter points, true motion 18° and (0.25, −0.15) m.
From 30° it lands on 18.000° exactly. With rejection off, the clutter drags it to 19.35°. From 63° or more it converges just as smoothly to a wrong answer (26° to 83°).
Point-to-plane ICP (Chen and Medioni, 1992) converges faster. Shift a wall of points 1 m apart by (0.70, 0.10). Point-to-point snaps to the wrong wall points and steps +0.10 m along the wall, the wrong way. Projecting each error on the wall’s normal leaves only the correct −0.10 m across it. LOAM (Zhang and Singh, RSS 2014) matches edge and plane features this way.
Symptom: in a 40 m loading dock, fitness is 0.97 and RMSE 0.021 m, the best on site. Yet the position slides metres along the dock.
Measure: the smallest eigenvalue of the point-to-plane information matrix JTJ. In our simulated scans it is 122 in a room, 15 in a corridor with its end wall in view, and 0 without it. Its eigenvector points along the corridor.
Fix: report no information along that eigenvector and let wheel odometry fill it (Zhang, Kaess and Singh, ICRA 2016). Deskew first: at 1.5 m/s a 0.1 s sweep smears 15 cm (Lesson 4).
Chapter 7
Pick the right motion estimator, and refuse to triangulate until the baseline earns it
A frontend has three ways to recover motion. The choice depends on what it already has.
| Estimator | Needs | Gives | Minimal s, N at w = 0.6 |
|---|---|---|---|
| 2-D to 2-D (essential matrix) | two images and K | rotation and the direction of t, no scale | 5, 57 samples |
| 3-D to 2-D (PnP) | a map and one image | full metric pose | 3, 19 samples |
| 3-D to 3-D (registration) | depth in both frames | full metric pose | 3, 19 samples |
The essential matrix (VNAV Lecture 7) starts the map. After that, ORB-SLAM tracks every frame by PnP against the local map: metric, six degrees of freedom, and 19 samples instead of 57.
New map points come from triangulation, and its error depends on the baseline. Call the depth Z, the baseline between the two camera centres B, the focal length f, and the pixel noise on the disparity σd. Depth is Z = fB/d, so a small disparity error becomes a depth error σZ:
sigma-Z equals Z squared times sigma-d, over f times B.
Square the depth Z, multiply by the pixel noise sigma-d, and divide by focal length times baseline. Double the depth and the error quadruples; double the baseline and it halves.
With made-up numbers: Z = 10 m, σd = 1 px, f = 500 px. One frame at 1.5 m/s and 30 Hz gives B = 0.05 m, so σZ = 100 / 25 = 4.0 m: 40% of the depth. Ten frames give B = 0.5 m and σZ = 0.4 m: 4%.
Two teal camera centres see one pink landmark. Each blue wedge is 1 px of noise; the purple overlap is where the triangulated point can be. Slide B down to 0.05 m.
Illustrative: f = 500 px, 1 px of noise per ray, the landmark centred between the cameras. The read-out uses the first-order formula; the drawn region uses the exact wedge geometry.
This is why frontends use keyframes: a wide baseline is the only way to make triangulation mean something. Gate on the parallax angle, not on metres. 1° at 10 m needs 10 × tan 1° = 17.5 cm of travel; at 2 m it needs 3.5 cm. ORB-SLAM adds a keyframe when the frame tracks at least 50 points but under 90% of the reference keyframe’s. Also, 20 frames must have passed, or the mapping thread must be idle.
Symptom: a parked robot pans its camera. VO reports 3 to 8 cm of motion per frame in random directions, and new landmarks appear from 0.5 m to 400 m deep.
Measure: median parallax across matches. With no translation it drops to the noise floor, 1 px / 500 px = 0.11°. With t = 0 the essential matrix is zero, so the solver returns noise.
Fix: below about 1°, estimate rotation only, give translation a huge covariance, and triangulate nothing.
Chapter 8
Stack four cheap checks on a loop closure, and find the one twin aisles cannot fool
Chapter 0's fold came from one accepted loop closure. A loop closure says “I am back where I was”, and it is the heaviest constraint a frontend sends. So the frontend runs it through a ladder of checks, each one cheap and each one aimed at a different lie.
Each check stops a different liar. A random look-alike rarely has matching geometry, and almost never three times in a row. Twin aisles are worse: identical shelving gives real geometric agreement, and it stays consistent for the whole aisle. Only the prior can tell them apart, because the twin is 12 m away.
Per 10,000 keyframe queries, three kinds of candidate flow down the funnel: green true revisits, red random look-alikes, red twin-aisle matches. Turn checks on one by one.
Illustrative rates we chose, not measured: 1,000 queries at true revisits, 1,000 in a twin aisle, 8,000 elsewhere. Appearance proposes 90% of revisits, 6% look-alikes and 60% twins. RANSAC passes 95%, 5% and 100%; three-in-a-row passes 90%, about 0% and 95%; the gate (radius 2.45 × 1.5 m) passes 99%, 0% and 0%.
With geometry alone, 24 random and 600 twin closures pass per 10,000 queries. Three in a row removes the random ones and keeps 570 twins. The pose-prior gate removes the twins and keeps 762 of 1,000 true revisits. Recall falls from 900 to 762 so that the false count reaches zero, and Chapter 0 says why that trade is right.
Symptom: a robot relocalizes into the wrong aisle twice overnight; the candidate had 84 inliers against a threshold of 40.
Measure: the Mahalanobis distance from the candidate to the odometry prediction. A twin 12 m away with σ = 1.5 m sits at 8 σ.
Fix: gate closures on the prior. Raising the inlier threshold cannot help: the twin's geometry is real.
Chapter 9
Wire matching, the ratio test and RANSAC into one machine, and test the formula against 100 runs
The bench runs a whole frontend on a synthetic scene. A matcher makes 300 putative matches, and a share ρ (rho) of them are wrong. The ratio test keeps each true match with the blue curve of Chapter 2 and each false one with the red curve. That sets how many survive, M, and the inlier ratio w. RANSAC with s = 2 then fits a 2-D rigid motion with your budget N, and refits on the inliers.
The right panel checks Chapter 4. The yellow curve is the formula's success chance, 1 − (1 − w²)N. The dots are 100 seeded runs of the real algorithm, counted as a success when the best model is within 1° of the truth.
Left: each surviving match as a line, green if true, red if false; the pink outline is the true motion, purple the estimate. Right: theory against runs. Start at ρ = 0.85 with τ = 1.00.
Illustrative scene: true motion 12° and (0.8, −0.4), inlier tolerance 0.16, the Chapter 2 curves for the ratios. Numbers in the text are for the first scene (seed 20240).
Five things to try, with the first scene’s numbers:
One currency runs through the whole frontend: the inlier ratio w. Detection, matching and gating raise it; RANSAC spends it. At 30 Hz, 99% success per frame still means 18 failed frames a minute, so verification is a ladder, not one step.
Symptom: pose jumps appear only in hard scenes, and nothing logs an error.
Measure: log w, the N the formula demands, and the N you ran, every frame. Three floats.
Fix: alarm when demanded N exceeds the budget, and mark that frame's pose untrusted instead of sending it.
Chapter 10
Keep the stages, their failures and the code in one place
The frontend turns sensor data into constraints and decides which ones to trust. FAST finds corners, a grid spreads them, and the ratio test and mutual check refuse ambiguous matches. A predicted pose shrinks the search. RANSAC turns agreement into a partition, at a cost exponential in the sample size. Direct tracking trades matches for brightness constancy; ICP trades them for a good start. Every stage has a failure that leaves its main metric green, so every stage logs a second number.
| Stage | Fails silently when | Log this | Healthy / alarm |
|---|---|---|---|
| Detection | keypoints cluster on one object | grid entropy H / 5.585 | above 0.7 / below 0.6 |
| Matching | repetitive structure | ratio-test rejection rate | about 30% / about 85% |
| RANSAC | a plane, or no translation | homography against fundamental score, RH | below 0.45 / above 0.45 |
| Direct tracking | an exposure step | pose jump against mean-intensity change | no correlation / one-frame spikes |
| ICP | a corridor, or a bad start | smallest eigenvalue of JTJ and its direction | 122 (room) / 0 to 15 (corridor) |
| Triangulation | pure rotation, short baseline | median parallax | above 1° / near 0.11° |
| Loop closure | twin places | Mahalanobis distance to the odometry prior | inside 2.45 σ / 8 σ |
python import numpy as np, math def ratio_mutual(D, tau=0.8): """D (nA, nB) descriptor distances -> kept (a, b) index pairs.""" j = np.argpartition(D, 2, axis=1)[:, :2] rows = np.arange(len(D)) order = np.argsort(D[rows[:, None], j], axis=1) j1, j2 = j[rows, order[:, 0]], j[rows, order[:, 1]] keep = D[rows, j1] < tau * D[rows, j2] # the row: Lowe's ratio keep &= D.argmin(axis=0)[j1] == rows # the column: mutual return np.stack([rows[keep], j1[keep]], 1) def ransac_iters(w, s, p=0.99): return math.ceil(math.log(1 - p) / math.log(1 - w ** s)) def best_rigid_2d(A, B): """Closed form: theta = atan2(sum of crosses, sum of dots), t = qbar - R pbar.""" a, b = A - A.mean(0), B - B.mean(0) th = math.atan2((a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0]).sum(), (a * b).sum()) R = np.array([[math.cos(th), -math.sin(th)], [math.sin(th), math.cos(th)]]) return R, B.mean(0) - R @ A.mean(0) def depth_sigma(Z, B, f=500.0, sigma_d=1.0): return Z * Z * sigma_d / (f * B) def grid_entropy(uv, W=1280, H=720, nx=8, ny=6): """Spread of keypoints, as a fraction of log2(nx*ny).""" c, _, _ = np.histogram2d(uv[:, 0], uv[:, 1], bins=[nx, ny], range=[[0, W], [0, H]]) p = c.ravel() / c.sum(); p = p[p > 0] return -(p * np.log2(p)).sum() / math.log2(nx * ny)
We ran each function in NumPy. The rigid fit returns 36.87° and (2, −1) on the three-point example. The iteration count is 27 for a line at w = 0.4, and 218 for the essential matrix at w = 0.5 and p = 0.999. The depth error at 10 m with 5 cm of baseline is 4.0 m. The matcher keeps the lab’s 87 matches, 85 of them correct.
Where it sits. The 30 Hz tracking path uses guided matching and PnP against a local map. A slower path, at keyframe rate, runs unguided matching for relocalization and loop candidates. Learned detectors and matchers (SuperPoint, LightGlue) fit best on that slower, wide-baseline path. Lesson 7 takes the constraints and optimizes them.
Now teach it: press Present or Teach and explain why one false loop closure folds the map while the optimizer reports success. Then go back to the aisle loop, predict the residual for pose 40 before you drag there, and switch on the gate.