From Two Photos to 3D

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 two views through bad matches

Fit

30%

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

One Photo Is Not Enough

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.

Cross two rays

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.

0.30 m

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:

  1. Detect points that are easy to find again, such as corners.
  2. Describe each point by a list of numbers.
  3. Match the lists across the two photos.
  4. Use geometry to throw out bad matches, then cross the rays.

The failure, as symptom, measurement and fix

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.

The road

  1. Gradients: an image is a function, and its slope finds edges.
  2. Corners: the Harris score keeps corners and drops edges.
  3. Matching: SIFT descriptors and the ratio test.
  4. Epipolar lines: the match must lie on one line (the hero's purple lines).
  5. The eight-point fit: how the lines come from the matches.
  6. RANSAC: fit through the outliers, and how many tries it takes (the hero's switch).
  7. Depth: triangulation and stereo.
  8. The pipeline: structure from motion, bundle adjustment, scale drift.
  9. Showcase: step RANSAC through the hero's matches one sample at a time.
  10. Field guide: terms, numbers, code and the credit.
Why can one calibrated camera not tell how far away a point is?

Chapter 1

An Image Is a Function, and Its Slope Finds Edges

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.

Say it aloud

I-u is about I at u plus one, v, minus I at u minus one, v, all over two.

Iu
I-u the horizontal slope of brightness at pixel (u, v), in grey levels per pixel.
I(u+1, v)
I at u plus one, v the brightness one pixel to the right.
I(u−1, v)
I at u minus one, v the brightness one pixel to the left.
/ 2
over two the two neighbours are two pixels apart, so divide by 2.
In plain words

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.

With numbers

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−1uu+1
v−1306090
v4090140
v+135120150

Turn an edge, read its gradient

Each square is a pixel; each blue arrow is its gradient. Turn the edge, add noise, then turn on smoothing.

60°
0

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 failure, as symptom, measurement and fix

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.

A pixel sits on a sharp vertical edge, dark on the left and bright on the right. What does its gradient look like?

Chapter 2

Corners: The Harris Detector

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.

WindowEigenvalues of MHarris score R
Flatboth smallnear 0
Edgeone large, one near 0negative
Cornerboth largelarge and positive

Eigenvalues cost time at every pixel. The determinant and the trace give the same verdict with a few multiplications.

Say it aloud

R equals det of M minus k times the trace of M, squared.

R
R the cornerness score of one pixel. Large and positive means corner.
det(M)
det of M A times B minus C squared. It equals the product of the two eigenvalues, so it is large only if both are large.
k
k a small constant. A common choice is 0.04.
tr(M)
the trace of M A plus B, the sum of the two eigenvalues.
2
squared the trace times itself. It grows on an edge, where one eigenvalue is big, and pushes R below zero.
In plain words

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.

With numbers

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.

Score every pixel

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.

0.04
0.25

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 failure, as symptom, measurement and fix

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.

Why does det(M) help Harris reject edges?

Chapter 3

Describe Each Corner, Then Match

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:

  1. Take a 16 by 16 sample array around the point.
  2. Turn it to the point's main gradient direction, so a turned camera gives the same list.
  3. Split it into a 4 by 4 grid of cells. In each cell, make a histogram of gradient directions with 8 bins.
  4. Join them: 4 × 4 × 8 = 128 numbers. Scale the list to length 1, cap each entry at 0.2, and scale again.

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.

Say it aloud

Keep the match if d-one over d-two is less than tau.

d1
d-one the distance from the descriptor to its closest descriptor in the other photo.
/
over divide. The result is the ratio, from 0 to 1.
d2
d-two the distance to the second closest descriptor.
<
is less than the test that keeps or drops the match.
τ
tau the threshold. Lowe dropped matches with a ratio above 0.8.
In plain words

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.

With numbers

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.

Slide the ratio threshold

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.

0.80

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 failure, as symptom, measurement and fix

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.

A match has a ratio d1/d2 of 0.3. What does that say?

Chapter 4

Epipolar Geometry: The Match Lies on a Line

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.

Slide the depth along the 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.

4.0 m

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.

Say it aloud

p-prime transpose, times F, times p, equals zero.

p′
p-prime the match in image 2, as (u′, v′, 1).
⊤
transpose lay the column on its side, so the product is a dot product.
F
F the fundamental matrix: 3 by 3, it holds the cameras' relative pose and both calibrations.
p
p the pixel in image 1, as (u, v, 1).
= 0
equals zero the match lies exactly on the line.
In plain words

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.

With numbers

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.

MatrixWorks onNeeds K?Free numbers
Fundamental Fraw pixelsno7
Essential E = [t]×Rcalibrated rays K−1pyes, from Lesson 85

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 failure, as symptom, measurement and fix

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.

What do you get when you multiply F by a pixel p of image 1?

Chapter 5

The Eight-Point Algorithm

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.

Say it aloud

f-hat is the f that makes the length of A f smallest, subject to the length of f being one.

f̂
f-hat our estimate of the nine entries of F.
argminf
the f that makes it smallest search over all columns f, keep the one with the least value.
‖ ‖
the length of the square root of the sum of squares.
A
A the n by 9 matrix, one row a per match.
f
f a candidate column of nine entries.
‖f‖ = 1
subject to the length of f being one this rules out f = 0, which solves A f = 0 and means nothing.
In plain words

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.

With numbers

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:

  1. Hartley normalization. Before you build A, shift each image's points so their centre is at 0, and scale them so their mean distance from 0 is √2. Solve, then undo the shift and scale.
  2. Rank 2. A true F has det F = 0, so all its lines meet at the epipole. Noise breaks this. Take the SVD of F, set the smallest singular value to 0, and rebuild.

Switch off a repair

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.

1.00 px

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 failure, as symptom, measurement and fix

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.

Why does the eight-point algorithm take the singular vector with the smallest singular value?

Chapter 6

RANSAC: Fit Through the Outliers

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.

  1. Pick s points at random.
  2. Fit the model to those s points.
  3. Count the inliers: points within a distance ε of the model.
  4. If that count beats the best so far, keep this model.
  5. Repeat N times. Then refit the best model on all its inliers.

Step RANSAC on a line

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.

40%

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.

Say it aloud

N equals log of one minus p, over log of one minus w to the s.

N
N the number of random tries. Round it up.
log
log the logarithm. It turns "chance to the power N" into "N times". Any base works if both use the same.
p
p the chance you want that at least one try is all inliers, such as 0.99.
w
w the share of inliers in the data, from 0 to 1.
s
to the s s is the points per try; w to the s is the chance that all s are inliers.
In plain words

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.

With numbers

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.

Count the tries

Each curve is N for one sample size, on a log scale. Pick s, slide w, and pick p.

0.50

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 failure, as symptom, measurement and fix

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.

A line fit (s = 2) at w = 0.5 and p = 0.99 needs 17 tries. What happens to N with an 8-point sample at the same w and p?

Chapter 7

Triangulation and Stereo Depth

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.

Say it aloud

Z equals f times B over d.

Z
Z the depth of the point, in metres.
f
f the focal length in pixels, from calibration.
B
B the baseline: the distance between the two cameras, in metres.
d
d the disparity: how many pixels the point shifts between left and right.
In plain words

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.

With numbers

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.

Push the point away

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.

8.0 m

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 failure, as symptom, measurement and fix

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.

A stereo rig sees a far object with a small disparity. What follows for its depth?

Chapter 8

Structure from Motion and Bundle Adjustment

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:

  1. Detect corners in both images (Chapter 2).
  2. Describe and match them, with the ratio test (Chapter 3).
  3. Fit F, or E with K, inside RANSAC (Chapters 5 and 6).
  4. Split E into the turn R and the step direction t (Chapter 4).
  5. Triangulate every inlier match (Chapter 7).
  6. Polish all poses and points together: bundle adjustment.

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.

Say it aloud

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.

minC, X
minimise over all C and X change every pose and every point to make what follows as small as possible.
Σi,j
the sum over i and j add one term for every camera i that saw point j.
qij
q-i-j the pixel where camera i saw point j.
π
pi the projection of Lesson 8: where a 3D point lands in a camera's image.
Ci
C-i the pose of camera i: its turn and position.
Xj
X-j the 3D position of point j.
‖ ‖2
squared length the pixel gap squared, in square pixels.
In plain words

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 numbers

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.

Watch the scale drift

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.

+1.00%

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 failure, as symptom, measurement and fix

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).

What does bundle adjustment minimise, and what can it not recover from one camera alone?

Chapter 9

Showcase: RANSAC Finds the Geometry

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.

Step RANSAC on real geometry

Press Step to make one try, or Run. Raise the wrong matches or tighten ε, then run again.

40%
2.0 px

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 failure, as symptom, measurement and fix

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

Field Guide

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.

TermMeaningNumber to remember
GradientIu ≈ (I(u+1, v) − I(u−1, v)) / 2(50, 30): length 58.3, 31°
HarrisR = det(M) − k · tr(M)2corner 200.4, edge −100, k = 0.04
SIFThistograms of gradient directions4 × 4 × 8 = 128 numbers
Ratio testkeep if d1 / d2 < ττ = 0.8: 90% of false matches gone
Epipolarp′⊤ F p = 0F: 7 free numbers; E: 5
Eight-pointsmallest singular vector of Anormalize, then rank 2
RANSACN = log(1 − p) / log(1 − ws)s 2: 17; s 5: 146; s 8: 1,177 (w 0.5, p 0.99)
StereoZ = f · B / d700 × 0.12 / 30 = 2.8 m
Bundle adjustmentminimise total reprojection errorone camera: shape, not scale

Checklist for a two-view front end

The core, in code

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

Keep going

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).

The takeaway. Depth needs two rays, and two rays need a correct match. Find points that can be found again, let geometry vote out the wrong matches, and only then cross the rays.

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.

Principles of Robot Autonomy I · Stanford AA 274A · Lesson 9: Features, RANSAC and Structure from Motion
Before: Camera Models · Next: Learning-Based Perception · Back to Gleams