Two photos of one scene hold its 3D shape, but only if you find the same points in both. Real matches are full of mistakes. With 30% wrong matches, a plain fit puts the true matches about 13 px off their lines. RANSAC keeps them under half a pixel.
Raise the share of wrong matches, then switch between a plain fit and RANSAC. Watch whether the purple lines pass through their dots. Then we build, piece by piece, corners, descriptors, the epipolar line, the eight-point fit, RANSAC, depth and the full pipeline.
You need Lesson 8 (the pinhole camera and K), a 2 by 2 matrix and a little Python. We build the rest from zero.
Lesson 9 of 15 in our follow-along of Stanford AA 274A, Principles of Robot Autonomy I. Every idea is re-taught here in our own words and devices. Before: Lesson 8, Camera Models and Calibration. Next: Lesson 10, Learning-Based Perception.
Fit
Illustrative toy: 40 points seen by two simulated 640 by 480 cameras (focal length 500 px), the second moved 0.6 m and turned 6 degrees. Matches get 0.5 px of noise; wrong matches land anywhere. Both fits use the normalized eight-point algorithm; RANSAC uses a 2 px threshold.
Chapter 0
Cross two rays to find a point, then feed one ray a wrong match
Take a photo of a mug on a table. Now say how far away the mug is. You cannot. Lesson 8 showed that a camera sends every point on one line through the lens to the same pixel. A toy mug at 10 cm and a big mug at 10 m can make the same dot.
So a pixel fixes a ray: a direction from the camera centre, with no distance. To get the distance back, you need a second photo from another place. Each photo gives one ray. The two rays cross at the point.
Seen from above: two cameras look at one pink point. Set the gap between them. Then turn on the wrong match and see where the rays cross now.
Illustrative toy: focal length 500 px, point 0.4 m right of the left camera and 3 m ahead. We stretch sideways distances so you can see the gap.
Work the number. The cameras stand 0.3 m apart and the point is 3.0 m ahead. Its two pixels differ by 50 px. Pick a pixel 15 px off in the second photo, and the rays cross 4.3 m out. One wrong match makes a phantom point 1.3 m behind the real one.
That is the hard part. Before you can cross two rays, you must know which dot in photo B shows the same point as a dot in photo A. This is the correspondence problem. The lesson builds the machinery in four steps:
The symptom is a 3D cloud with points floating in empty air. To measure it, project each 3D point back into both photos and count the points that land far from their pixels. The fix is to reject matches that break the geometry of the two views, which is what RANSAC does in Chapter 6.
Chapter 1
Turn an edge and watch the brightness slope turn with it
To a robot, a grey image is a function. Give it a column u and a row v, and it returns a brightness from 0 (black) to 255 (white). Call it I(u, v). A flat wall gives the same number everywhere. The useful parts of an image are where the number changes: edges, corners, texture.
The image has no formula, so we cannot differentiate it the calculus way. We subtract neighbours. Call the horizontal slope Iu: how fast brightness rises as you step right. The vertical slope Iv is the same, one row down. Together they form the gradient, an arrow that points toward brighter pixels.
I-u is about I at u plus one, v, minus I at u minus one, v, all over two.
Subtract the left neighbour from the right neighbour and halve it. That is I-u. Do the same with the pixels below and above to get I-v.
In the patch below, the centre pixel has 40 on its left and 140 on its right: I-u = (140 − 40) / 2 = 50. Above is 60 and below is 120: I-v = (120 − 60) / 2 = 30. The arrow (50, 30) has length √(2500 + 900) = 58.3 and points 31° below the right-hand direction.
| u−1 | u | u+1 | |
|---|---|---|---|
| v−1 | 30 | 60 | 90 |
| v | 40 | 90 | 140 |
| v+1 | 35 | 120 | 150 |
Each square is a pixel; each blue arrow is its gradient. Turn the edge, add noise, then turn on smoothing.
Illustrative toy: a soft edge from 30 to 230 grey levels. Smoothing is a 3 by 3 average before the differences. The read-out reports the ringed centre pixel.
The arrows are long across the edge and near zero on flat ground. An edge runs at right angles to its gradient.
The symptom is a flat region full of strong fake arrows. To measure it, read the gradient length where the image should be flat. The fix is to blur first with a small Gaussian, then take differences. The Sobel filter does both in one 3 by 3 pass.
Chapter 2
Score every pixel and keep only the places that change in every direction
Slide a small window along an edge and the view inside barely changes. One stretch of edge looks like every other stretch. This is the aperture problem, and it makes edges poor landmarks. A corner is different: move the window any way and the view changes. So the second photo shows a corner in a way you can find again.
Harris and Stephens (1988) turned that test into a number. Take a small window around a pixel and add up three sums over its pixels. A is the sum of Iu squared, B the sum of Iv squared, and C the sum of Iu times Iv. Put them in a 2 by 2 matrix M = [A C; C B], the structure tensor. Its two eigenvalues measure how much the window changes along its two main directions.
| Window | Eigenvalues of M | Harris score R |
|---|---|---|
| Flat | both small | near 0 |
| Edge | one large, one near 0 | negative |
| Corner | both large | large and positive |
Eigenvalues cost time at every pixel. The determinant and the trace give the same verdict with a few multiplications.
R equals det of M minus k times the trace of M, squared.
Multiply A by B and subtract C squared to get det. Add A and B to get the trace. Take k times the trace squared away from det. What is left is R.
A window has three pixels with gradients (4, 0), (0, 3) and (2, 2). Then A = 20, B = 13 and C = 4. So det = 20 × 13 − 16 = 244 and trace = 33. R = 244 − 0.04 × 1089 = 200.4: a corner. An edge window with (4, 0), (5, 0), (3, 0) gives A = 50, B = 0, C = 0. R = −0.04 × 2500 = −100: rejected.
Left: the image, with blue rings on the corners found. Right: R at every pixel, blue where positive, grey where negative. Change k and the threshold.
Illustrative toy: a 3 by 3 window, centred differences, and a local-maximum check. The diamond is the square turned 45 degrees.
Turn the square into a diamond and its corners still fire: the eigenvalues do not care how the corner is turned. Zoom in and a corner becomes a gentle curve, so Harris is not scale-invariant. SIFT fixes that by searching over many blur scales.
The symptom is a corner set that changes when the robot drives closer. To measure it, count the share of corners found again after a zoom: the repeatability. The fix is to detect at several scales.
Chapter 3
Slide the ratio threshold and trade more matches against cleaner ones
Harris gives locations: "a corner at pixel (412, 88)". You cannot match a location alone across two photos. Each corner needs a descriptor: a list of numbers that sums up the patch around it. It should stay the same when the view changes and differ between different points.
Raw pixels fail. Turn the camera a few degrees and every pixel in the patch moves. Lowe's SIFT descriptor (2004) uses the directions of the gradients instead. Its steps:
To match a descriptor from photo A, find the closest descriptor in photo B by straight-line distance. Repeated texture breaks this. A row of identical windows gives several near-identical descriptors, and the closest one is often wrong. Call the distance to the closest d1 and to the second closest d2.
Keep the match if d-one over d-two is less than tau.
Find the best and the second-best candidate. Divide the best distance d-one by the runner-up distance d-two. Keep the match only if the best is clearly better, so the ratio is below tau.
d-one = 0.18 and d-two = 0.21 give 0.86. That is above tau = 0.8, so drop it: the best barely wins. d-one = 0.12 and d-two = 0.40 give 0.30: keep it. In Lowe's test, a 0.8 threshold removed 90% of the false matches and lost under 5% of the correct ones.
Lines join each feature in view A to its closest descriptor in view B. Green is a correct match kept, red a wrong match kept, faint a match dropped. The squares are a row of identical windows.
Illustrative toy: 14 features with hand-set distance ratios. The pattern (distinct features have low ratios, repeated ones high) follows Lowe's Figure 11; the values are ours.
The symptom is matches that jump between identical windows. To measure it, count the matches that a geometric check later rejects. The fix is the ratio test first, then RANSAC for the wrong matches that pass it.
Chapter 4
Pick a pixel, slide its unknown depth, and watch the match run along one line
Two cameras with centres O and O′ see a point P. P lands on pixel p in image 1 and on p′ in image 2. The five points P, O, O′, p and p′ lie in one plane, the epipolar plane. Three more names:
Here is the gain. We do not know how far away P is, so p′ could be anywhere on the ray's picture in image 2. That picture is a line. The search for a match drops from the whole image to one line.
Tap the left image to pick a pixel (yellow). Slide the depth of the point: its match in the right image moves, but never leaves the purple line. Change how the second camera moved.
Illustrative toy: focal length 500 px, image 640 by 480. "Step right" is 0.2 m sideways; "Step forward" is 0.9 m ahead; "Step and turn" is 0.6 m with a 6 degree turn.
Write a pixel (u, v) as the column p = (u, v, 1). Write a line au + bv + c = 0 as the column (a, b, c). A point lies on a line when the dot product of the two columns is zero. A 3 by 3 matrix F, the fundamental matrix, turns a pixel p of image 1 into its epipolar line F p in image 2.
p-prime transpose, times F, times p, equals zero.
Multiply F by p. The result is the line l′ = F p in image 2. Take the dot product of p-prime with that line. If it is zero, p-prime sits on the line, so the match is possible.
Focal length 500 px, centre (320, 240), second camera 0.2 m to the right. The point (0.5, 0.25, 2.5) m lands at p = (420, 290) and p′ = (380, 290). Up to scale, F = [0 0 0; 0 0 1; 0 −1 0], so F p = (0, 1, −290): the row v′ = 290. Then p′ · F p = 290 − 290 = 0.
| Matrix | Works on | Needs K? | Free numbers |
|---|---|---|---|
| Fundamental F | raw pixels | no | 7 |
| Essential E = [t]×R | calibrated rays K−1p | yes, from Lesson 8 | 5 |
One formula ties them: F = K−⊤ E K−1. Here K is the camera matrix of Lesson 8, R the turn and t the step between the cameras. From E you can recover R and the direction of t. F has 7 free numbers: 9 entries, minus 1 for scale, minus 1 because det F = 0.
The symptom is epipolar lines that miss good matches by a steady few pixels. To measure it, average the distance from each match to its line. A wrong K or lens distortion is the usual cause; the fix is to recalibrate as in Lesson 8.
Chapter 5
Fit F from matches, then switch off each repair and watch the lines go wrong
We do not know how the camera moved, so we do not know F. We do have matches. Each match (p, p′) gives one equation about the nine entries of F. Write p = (u, v, 1) and p′ = (u′, v′, 1), and multiply out p′⊤F p = 0. The equation is linear in the entries, with this row of known numbers in front:
a = (u′u, u′v, u′, v′u, v′v, v′, u, v, 1)
Call the nine entries of F, read row by row, the column f. Then each match says a · f = 0. Stack n rows into an n by 9 matrix A. Scaling F does not change the lines, so only 8 numbers are free, and 8 matches fix them.
f-hat is the f that makes the length of A f smallest, subject to the length of f being one.
Stack one row per match into A. Among all columns f of length one, pick the one that makes A f nearest to zero. It is the singular vector of A with the smallest singular value: the last row of V⊤ in the SVD. Fold it back into a 3 by 3 F.
The match p = (100, 50), p′ = (110, 48) gives a = (11000, 5500, 110, 4800, 2400, 48, 100, 50, 1). The entries run from 11000 down to 1. That spread is why the first repair below exists.
The raw answer needs two repairs:
Image 2 of a camera that stepped forward and a little right, so the true lines meet inside the image at the pink ring. Blue dots are 12 matches; purple lines come from the fitted F. Switch each repair off.
Illustrative toy. This page solves through A⊤A with a small eigen solver, which squares the spread of the numbers. Over 20 draws of noise at 1 px, normalization cuts the median miss from 6.2 px to 1.1 px.
The symptom is epipolar lines that wander and do not share one epipole. To measure it, take the median distance from each match to its line, and the smallest singular value of F. The fix is both repairs. OpenCV's cv2.findFundamentalMat does them for you.
Chapter 6
Step through random tries and count how many it takes
Your matcher returns 200 matches. Perhaps 140 are right, the inliers, and 60 are wrong, the outliers. Least squares adds up squared errors. One match 300 px off weighs as much as 90,000 matches 1 px off, so a few outliers pull the fit anywhere.
RANSAC (random sample consensus) lets the data vote. A fit to a few good points wins many votes; a fit that holds one bad point wins few. One fit needs s points: 2 for a line, 8 for F.
The warm line is this try's pair; green dots are its inliers. Purple is the best so far, and the grey dashed line is least squares. Press Step, or Run.
Illustrative toy: 60 points, inliers with 1.2 units of noise around a pink true line, ε = 3 units. Run stops at the N of the formula below for the share of inliers it has found.
How many tries N are enough? Call the share of inliers w. One random point is an inlier with chance w, so all s points are with chance ws. A try fails with chance 1 − ws, and N tries all fail with chance (1 − ws)N. Call the success you want p, and set that failure chance to 1 − p.
N equals log of one minus p, over log of one minus w to the s.
Raise w to the power s to get the chance of a clean try. Take the log of one minus that, and the log of one minus p. Divide, and round up. That is N.
A line (s = 2), half the points wrong (w = 0.5), and p = 0.99. Then ws = 0.25 and N = log 0.01 / log 0.75 = −4.605 / −0.288 = 16.01. Round up: 17 tries. (16 tries reach only 98.998%.) The eight-point F (s = 8) at the same w needs 1,177.
Each curve is N for one sample size, on a log scale. Pick s, slide w, and pick p.
Exact values of the formula, rounded up. The five-point solver for E is Nistér's (2004).
N grows fast with s, so calibrated robots prefer the five-point solver for E. And N depends only on w, s and p, not on the number of points.
The symptom is a fit that is right on most runs and wrong on some. To measure it, rerun with new random seeds and compare the inlier counts. The fix is to update N from the best inlier share so far. Set ε from the real noise, often 1 to 3 px.
Chapter 7
Push a point away and watch one pixel of error grow into metres
Now we know the matches and the cameras' relative pose. Each match gives two rays in one frame, and the 3D point is where they cross. This is triangulation. With noise the two rays are skew: they pass close but never touch. So we pick the 3D point whose pictures land closest to the measured pixels. That distance in pixels is the reprojection error.
The easiest case is a stereo rig: two cameras side by side, facing the same way. After rectification, a warp that makes the two images exactly parallel, each match sits on the same row. The shift along the row is the disparity d = uL − uR, in pixels. Call the focal length f, in pixels, and the distance between the cameras B, in metres.
Z equals f times B over d.
Multiply the focal length f by the baseline B. Divide by the disparity d. Near points shift a lot, so their Z is small. Far points barely shift, so their Z is large.
f = 700 px, B = 0.12 m, uL = 410, uR = 380. Then d = 30 px and Z = 84 / 30 = 2.8 m. At d = 60, Z = 1.4 m. At d = 3, Z = 28 m, and at d = 4, Z = 21 m: one pixel moves the answer by 7 m.
Two cameras look at a pink point. The purple band holds every depth the rig could report if the disparity is off by one pixel. Slide the depth; pick a baseline.
Illustrative toy with f = 700 px. We stretch sideways distances so you can see the rays; depth is to scale.
The band grows with the square of the depth: one pixel moves Z by about Z2 / (fB). At 2.8 m that is 0.09 m; at 28 m it is 9.3 m. A wider baseline shrinks the band, but the cameras then see less of the same scene.
One moving camera has a worse problem. The essential matrix gives the direction of the step t, not its length. Double the scene and double the step, and both photos stay the same. A single camera gets shape, not size: the scale ambiguity.
The symptom is far points that jump in depth from frame to frame. To measure it, plot the spread of Z against Z. The fix is a wider baseline, sub-pixel disparity, or a range limit for the depths you trust.
Chapter 8
Chain the steps, polish them together, and watch the scale drift away
Structure from motion (SfM) takes m photos of n fixed points, shot from unknown places. It recovers the m camera poses (the motion) and the n 3D points (the structure). Two views at a time, the pipeline is every chapter so far:
Two-view answers carry small errors, and with many views they disagree. Bundle adjustment moves every camera pose and every 3D point at once to make the total reprojection error smallest. Call camera i's pose Ci, point j's position Xj, and the pixel where camera i saw point j qij.
Minimise over all C and X the sum over i and j of the squared length of q-i-j minus pi of C-i and X-j.
For each camera i and each point j it saw, project X-j through C-i with pi. Measure the gap to the real pixel q-i-j and square it. Add every gap. Nudge all C and X to shrink the total.
With made-up numbers: two observations miss by (1.5, −0.5) px and (0.3, 0.4) px. The total is 2.25 + 0.25 + 0.09 + 0.16 = 2.75 square pixels. A solver such as Levenberg-Marquardt moves the poses and points until the total stops falling.
Chain many two-view steps with one camera, and each step guesses its own scale a little wrong. The errors multiply: scale drift. With a 1% error per frame, the scale after 50 frames is 1.0150 = 1.64: each new step looks 64% longer than it is.
Pink is the true path around a block; purple is what the camera estimates. Set the scale error per frame and compare one camera with a stereo pair.
Illustrative toy: 60 frames around a 20 m by 10 m block. One camera multiplies its scale by (1 + error) each frame. The stereo pair measures metric scale every frame, so its error does not add up.
The symptom is a map that slowly grows or shrinks. To measure it, compare a known distance, such as a corridor's length, at the start and end. The fix is a source of metric scale: a stereo rig, an IMU, wheel odometry, or a loop closure that snaps the path back (Lesson 11).
Chapter 9
Run the robust two-view fit one sample at a time
This is the hero's fit, opened up. Each step picks 8 matches at random (warm rings), fits F with the normalized eight-point algorithm, and counts the matches within ε of their epipolar lines. The best F so far draws its purple lines. When the tries reach N, RANSAC refits on every inlier.
Press Step to make one try, or Run. Raise the wrong matches or tighten ε, then run again.
Illustrative toy: the hero's 40-point scene. RANSAC updates N after every new best, from the inlier share it has found, with p = 0.99 and s = 8, capped at 3,000.
What to look for. At 40% wrong matches, most tries include an outlier and win few votes. The first clean sample jumps the count past 20, and N drops to fit the new inlier share. Tighten ε below the noise and true matches fail the vote. Loosen it to 6 px and a few wrong matches sneak in as inliers.
Swap the line for F, and the distance to the line for the distance to the epipolar line. That is the front end of the visual SLAM systems in Lesson 11.
The symptom is a fit that keeps a few bad matches. To measure it, plot each inlier's distance to its line: real inliers cluster near the noise level. The fix is ε at about two to three times the pixel noise, then a refit on the inliers.
Chapter 10
Keep the terms, the numbers and the code in one place
A pixel is a ray. Two rays cross at a point, if you find the same point in both photos. Corners give points you can find again. Descriptors and the ratio test match them. The epipolar line, the eight-point fit and RANSAC throw out wrong matches. Triangulation gives depth, and bundle adjustment polishes it all.
| Term | Meaning | Number to remember |
|---|---|---|
| Gradient | Iu ≈ (I(u+1, v) − I(u−1, v)) / 2 | (50, 30): length 58.3, 31° |
| Harris | R = det(M) − k · tr(M)2 | corner 200.4, edge −100, k = 0.04 |
| SIFT | histograms of gradient directions | 4 × 4 × 8 = 128 numbers |
| Ratio test | keep if d1 / d2 < τ | τ = 0.8: 90% of false matches gone |
| Epipolar | p′⊤ F p = 0 | F: 7 free numbers; E: 5 |
| Eight-point | smallest singular vector of A | normalize, then rank 2 |
| RANSAC | N = log(1 − p) / log(1 − ws) | s 2: 17; s 5: 146; s 8: 1,177 (w 0.5, p 0.99) |
| Stereo | Z = f · B / d | 700 × 0.12 / 30 = 2.8 m |
| Bundle adjustment | minimise total reprojection error | one camera: shape, not scale |
python import cv2, numpy as np sift = cv2.SIFT_create() kA, dA = sift.detectAndCompute(imgA, None) # detect + describe kB, dB = sift.detectAndCompute(imgB, None) pairs = cv2.BFMatcher().knnMatch(dA, dB, k=2) good = [m for m, n in pairs if m.distance < 0.8 * n.distance] # ratio test p1 = np.float32([kA[m.queryIdx].pt for m in good]) p2 = np.float32([kB[m.trainIdx].pt for m in good]) E, mask = cv2.findEssentialMat(p1, p2, K, method=cv2.RANSAC, prob=0.999, threshold=1.0) _, R, t, mask = cv2.recoverPose(E, p1, p2, K, mask=mask) # turn R, step direction t M1 = K @ np.hstack([np.eye(3), np.zeros((3, 1))]) M2 = K @ np.hstack([R, t]) X = cv2.triangulatePoints(M1, M2, p1.T, p2.T) cloud = (X[:3] / X[3]).T # 3D points, up to scale
Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's ninth lesson in our own words, devices and toy numbers. SIFT facts are from Lowe, "Distinctive Image Features from Scale-Invariant Keypoints" (IJCV, 2004).
Now press Present or Teach. Explain from memory the Harris score, the ratio test, the epipolar line, the two repairs, the RANSAC count and Z = fB/d. Then go back to the hero, set 50% wrong matches, and say why the plain fit fails.