A camera sees a straight lane edge at 25°. Of its 40 edge pixels, 20 are glare. Least squares on all 40 tilts the edge to 16.8°. RANSAC fits a line to 2 random pixels at a time, keeps the line that 18 pixels agree with, and finds 25.0° after 21 tries.
Switch between least squares and RANSAC. Then slide the share of glare up to 70%. Then we build it piece by piece: the loop, the sample, the tries, the threshold, the refit, better scores, and the 8-point algorithm inside RANSAC.
You need Lecture 7 (matches, F, E and the 8-point algorithm), what a probability is and a little Python. We build the rest from zero.
Lecture 8 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 7, two-view geometry. Next: Lecture 9, estimation and nonlinear least squares.
Illustrative toy image: 40 pixels, good ones with 2 px of Gaussian noise, glare spread over the top half. Least squares here minimises perpendicular distances. RANSAC uses a 3.9 px threshold (1.96σ), stops at 99% confidence, then refits on the pixels it kept. It runs in your browser.
Chapter 0
Drag one wrong pixel away from the edge and watch it take over the fit
Lecture 7 turned matches into a camera pose. It assumed every match was right. Real matchers are wrong often: a repeated window, a reflection, a moving car. In a typical pair of frames, a large share of the matches can be wrong, and nothing in the match says which.
Start with the smallest case: fit a straight line to edge pixels. Least squares picks the line that makes the sum of squared distances smallest. Square a distance and big misses grow fast. One wrong pixel far away can outweigh every good one.
Twenty blue pixels lie on the lane edge. Drag the glare pixel up, or use the slider. The bars below show each pixel's share of the squared error.
Illustrative toy image: good pixels have 2 px of noise; the glare sits at the right of the image. The fit minimises perpendicular squared distances.
Name the gap from pixel i to a candidate line ri, its residual. Least squares adds up the squares.
J equals the sum over i of r-i squared.
For a candidate line, measure each pixel's distance r-i. Square each one and add them to get J. Turn the line until J is as small as it can be.
A good pixel sits about 2 px off the edge, so it adds about 4 px². A glare pixel 100 px off adds 10,000 px². One glare pixel weighs as much as 2,500 good ones, so the fit tilts toward it.
In the device, one glare pixel 100 px above the edge carries 92% of the squared error and turns the edge by 1.4°. Four glare pixels turn it by 4.6°. Statisticians call the share of wrong data an estimator survives its breakdown point. For least squares it is zero: one pixel, moved far enough, moves the line as far as it likes.
The fix is a change of question. Do not ask which line is closest to every pixel. Ask which line the most pixels agree with. That is RANSAC, random sample consensus, from Fischler and Bolles (1981).
Symptom: a pose or a line that jumps when one new match arrives.
Measure: each residual's share of J. If one or two matches carry most of it, they own the answer.
Fix: find the agreeing majority first (Chapter 1), then fit only to it (Chapter 6).
Chapter 1
Step the loop one try at a time and watch a lucky pair win the vote
Two pixels fix a line. If both are good, that line lies close to the true edge, and most good pixels sit near it. If either is glare, the line points somewhere random and almost no pixel agrees. So draw two pixels at random, again and again, and count the agreement each time.
The hero's 40 pixels, half glare. Each try rings two pixels in warm, draws their line and its band, and counts who is inside. The solid purple line is the best so far.
The hero's data and the same random draws: the band is 3.9 px on each side. Bars below the image show each try's count.
Write the vote as a formula. Call the threshold t. For a candidate line θ ("theta"), give pixel i one point if its residual is under t, else nothing.
S of theta equals the sum over i of one if the size of r-i of theta is less than t, and zero otherwise.
Measure every pixel's distance r-i to the line theta. Give a pixel 1 point if it is closer than t. Add the points. That total S is the line's vote count. A glare pixel 100 px away costs the line nothing; it just does not vote.
The hero's data: try 1 draws two glare pixels and S = 5. Try 4 draws two good pixels that sit close together, and S = 3. Try 9 draws two good pixels far apart, and S = 18. That line wins.
The vote is asymmetric. A wrong line collects 2 to 5 votes by chance. The right line collects nearly all 20 good pixels. That gap is what lets RANSAC ignore the glare: it never fits to it, it only fails to count it.
Symptom: the winning line has a consensus set barely bigger than the losers'.
Measure: the best count against the typical count of a random try (2 to 5 here).
Fix: run more tries (Chapter 3), or check the threshold (Chapter 4). A small margin means no try found a clean pair yet.
Chapter 2
Choose a model and watch the chance of a clean sample fall with each extra match
The minimal sample is the fewest data that fix the model. Call its size s. Count the unknowns, then divide by how many equations one datum gives.
Why fewest? Call the share of good data the inlier ratio w. A sample is clean when every datum in it is good.
P-clean equals w to the s.
The first datum is good with chance w. So is the second, and every one after. All s good together: multiply w by itself s times.
With w = 0.6: a line (s = 2) gives 0.36 and a homography (s = 4) gives 0.13. E by five points gives 0.078 and F by seven gives 0.028. The 8-point algorithm gives 0.017, about 1 sample in 60.
Each row is one random sample: green dots are good data, red are wrong. A row with no red is clean. Choose a model and move the inlier ratio.
Illustrative random draws from a seed. The bar is the exact ws.
Each extra datum multiplies the chance by w again. That is why the five-point solver matters: at w = 0.5 a clean 8-sample comes once in 256 tries, a clean 5-sample once in 32.
A clean sample can still fail. Two good pixels side by side give a line whose angle the noise decides: that was try 4 in Chapter 1. Eight matches on one flat wall leave F undetermined (Lecture 7). Such a sample is degenerate (Chapter 8).
Symptom: RANSAC on F needs thousands of tries where E needed a hundred.
Measure: ws for each solver at your inlier ratio.
Fix: use the smallest solver that fits the problem: five points for a calibrated camera, four for a plane.
Chapter 3
Pick a confidence and watch the budget explode as good data gets rare
RANSAC succeeds if at least one try is clean. Choose how sure you want to be: a confidence p, such as 0.99. Call the number of tries N.
One try fails with chance 1 − ws. Tries are independent, so all N fail with chance (1 − ws)N. Ask that this be at most 1 − p, take logs, and divide. Both logs are negative, so the inequality flips once and the ratio is positive.
N equals log of one minus p, divided by log of one minus w to the s. Round it up.
Work out the chance that one try fails, 1 minus w to the s. Ask how many times you can multiply that chance by itself before it drops under 1 minus p. That count is N.
w = 0.5, s = 4, p = 0.99: log(0.01) / log(0.9375) = 71.4, so N = 72. Fischler and Bolles worked w = 0.5, s = 4 at 90% confidence: log(0.1) / log(15/16) = 35.7.
Five warm curves, one per sample size, on a log scale. Pick s and move w and p. Then press Test: the page runs 2,000 RANSAC searches of N tries each and counts how many found a clean sample.
Exact formula. The test draws each datum good with chance w, the formula's own model. With a finite set drawn without repeats the per-try chance is a little lower: 120 good of 200 gives 0.0153 for s = 8, not 0.0168.
| Inlier ratio w | Line, s = 2 | H, s = 4 | E, s = 5 | F, s = 7 | 8-point, s = 8 |
|---|---|---|---|---|---|
| 0.9 | 3 | 5 | 6 | 8 | 9 |
| 0.7 | 7 | 17 | 26 | 54 | 78 |
| 0.5 | 17 | 72 | 146 | 588 | 1,177 |
| 0.3 | 49 | 567 | 1,893 | 21,055 | 70,188 |
The table uses p = 0.99. At w = 0.5 the 8-point loop needs 1,177 tries and the five-point loop 146. At w = 0.3 the 8-point loop needs 70,188. The Monte Carlo test lands on p: for w = 0.5, s = 4 and N = 72, 99.1% of 20,000 simulated searches found a clean sample in our check.
Symptom: RANSAC returns a bad model now and then, on data that usually works.
Measure: the tries you allowed against N at the real inlier ratio. A cap of 1,000 at w = 0.4 with s = 8 succeeds only about 1 time in 2.
Fix: a smaller solver, a better matcher (a higher w), or a cap set from the formula.
Chapter 4
Slide the threshold across two piles of residuals and watch good pixels leave or glare get in
The vote needs a threshold t. Too tight, and good pixels with ordinary noise fail the test. Too loose, and glare that happens to sit near a wrong line joins its vote. Look at two piles of residuals, measured from the true edge: the good pixels pile up near zero, the glare spreads out.
Bars are residuals from the true edge for 2,000 good pixels and 2,000 glare pixels. Slide the threshold t. Green bars are good pixels kept; red bars are glare let in.
Illustrative toy pixels from a seed. Good pixels have Gaussian noise σ in u and v; glare covers the top half of the image, as in the hero.
Set t from the noise. Say each good pixel has Gaussian noise σ ("sigma") in each direction. Its distance to the true line is then Gaussian too, with spread σ. Pick the share of good data to keep, α ("alpha"), usually 0.95. A chi-square value tells how big a sum of m squared standard Gaussians gets with that chance; m is how many numbers the residual has.
t squared equals chi-squared m of alpha, times sigma squared.
Decide how many good pixels you are willing to lose, say 5%. Look up the chi-square value for that share. Multiply by sigma squared, then take the square root: that is t.
The hero: σ = 2 px, m = 1, α = 0.95. t2 = 3.84 × 4 = 15.4 px², so t = 3.9 px, which is 1.96σ. A homography with the same noise would use t = 2.45σ = 4.9 px.
In the device at σ = 2 px, t = 3.9 px keeps 95% of the good pixels and lets in about 1.5% of the glare. Set t to σ, 2 px, and 31% of the good pixels drop out. Set t to 3σ and 99.7% stay. Fischler and Bolles set it the practical way: perturb the data, measure the spread of errors, and put t one or two standard deviations beyond the average.
Watch the units. A threshold in pixels does not carry over to normalised coordinates: divide it by the focal length. The raw epipolar residual of Lecture 7 has no unit at all. OpenCV's findEssentialMat and findFundamentalMat take the threshold in pixels, and their documentation suggests 1 to 3.
Symptom: the best consensus set is small even after many tries, though the matches look good.
Measure: t against σ. Below 1σ, a third of good data fails the test.
Fix: measure σ on known-good data, set t = 1.96σ (or 2.45σ for a 2D error), and keep t in the residual's units.
Chapter 5
Run the loop and watch the budget of tries collapse the moment a big vote arrives
The formula needs w, and you do not know w before you start. But every try teaches you something. The best consensus set so far is a group of pixels that agree, so the true inlier ratio is at least its share. Call the size of the best set |S*| ("the size of S-star") and the number of data n.
w-hat equals the size of S-star, divided by n.
Each time a try beats the best count, divide the new count |S*| by n to get w-hat. Put w-hat into the formula of Chapter 3 to get a new budget of tries. Stop when the tries so far reach it.
The hero: try 1 gets 5 votes, so w-hat = 5 / 40 = 0.125 and the budget is 293. Try 9 gets 18 votes: w-hat = 0.45 and the budget drops to 21. The loop stops after try 21.
The warm step line is the budget after each try, on a log scale. Green bars are the best count so far. Press Run, then try another share of glare.
The hero's toy image and threshold, p = 0.99, line (s = 2). The budget starts at a cap of 2,000.
w-hat is never too high, because glare rarely agrees with anything. So the budget is safe: if anything, it is too big. That is the version OpenCV ships: its RANSAC loop recomputes the number of iterations each time it finds a better model.
There is a catch. The formula assumes one clean sample is enough. With noise, a clean but cramped sample, such as two good pixels side by side, gives a line that only part of the good data agrees with. Then |S*| stays low, w-hat stays low, and the loop runs longer than the formula promised. Chum, Matas and Kittler (2003) found exactly this: RANSAC drew far more samples than the formula predicted. Chapter 6 fixes it.
Symptom: run time swings from 1 ms to 100 ms between similar frames.
Measure: the try at which the best count jumped, and w-hat at the end.
Fix: keep the adaptive stop, add a hard cap from your time budget, and run local optimisation (Chapter 6) so w-hat climbs to the truth fast.
Chapter 6
Start from a clean but cramped pair and watch each refit pull in more of the good pixels
The winning line passes exactly through two noisy pixels. Its angle carries their noise, and when the two sit close, a small shift turns the line a lot. The loop's job is to find the right group. It is not to fit it well.
So finish with a refit: least squares again, but only over the consensus set. Call the best set S*.
theta-hat equals the argmin over theta of the sum, over i in S-star, of r-i of theta squared.
Keep only the pixels in S-star. Run least squares on them, exactly as in Chapter 0. The glare is gone, so squaring is safe again, and the noise of 18 pixels averages out.
On the hero's data, the best pair gives 24.8°. The refit on its 18 pixels gives 25.0°. We simulated 20,000 sets of 20 good pixels with σ = 2 px. A line through 2 random good pixels missed by a median of 0.62°; the refit on all 20 by 0.10°.
A refit can also change the vote. The better line may bring in good pixels the cramped pair missed. Count again, refit again, until the set stops growing.
Chum, Matas and Kittler (2003) put this inside the loop and called it LO-RANSAC, locally optimised RANSAC. It runs only when a try sets a new best, so it costs little. On their epipolar and homography tests it was two to three times faster than plain RANSAC and found 10 to 20% more inliers. Its tries then matched the formula's prediction.
Warm rings mark a clean pair of good pixels. Press Refit to fit to the current inliers and count again. Draw a new pair to see a cramped one.
The hero's toy data at 50% glare, t = 3.9 px. The refit is least squares on perpendicular distances.
In the device, a clean pair 24 px apart gets 3 votes. Four refits grow the vote to 5, 12, 16 and 18, and the fifth changes nothing. The closest pair, 2.4 px apart, stays at 3 no matter how often you refit: its line points the wrong way, and the 3 pixels near it agree with that.
Symptom: the final model is a little off, and its inlier set leaves out good data near the edges of the band.
Measure: the inlier count before and after one refit. If it grows, the minimal-sample model was holding the vote back.
Fix: always refit, and repeat refit and recount until the set stops growing; in the loop, that is LO-RANSAC.
Chapter 7
Loosen the threshold until counting calls a tie, then let MSAC break it
Counting treats an inlier at 0.1 px and one at 3.8 px the same. With a tight threshold that rarely matters. With a loose one, a tilted line can collect as many votes as the right one. Then counting cannot tell them apart.
Torr and Zisserman (2000) gave two fixes. MSAC scores a line by its squared residuals, but caps each one at t2. An inlier pays its own square; an outlier pays the cap, at any distance.
C of theta equals the sum over i of the minimum of r-i squared and t squared.
For each pixel, square its distance r-i. If that is bigger than t squared, write t squared instead. Add them up to get C. A tight inlier costs little, a loose one costs more, and glare costs the same fixed amount wherever it is.
The device at t = 20 px: the right line A keeps 20 pixels and the line B tilted 2° keeps 21, so counting picks B. MSAC gives A a cost of 8,074 px² and B 8,803 px², so MSAC picks A.
Line A is the right edge. Line B is A turned 2°. Slide the threshold and choose the score. The bars compare the two lines.
The hero's toy data at 50% glare. A is least squares on the 20 good pixels; B is A turned 2° about their centre.
Does it matter over many runs? Our toy test used 300 images at 50% glare, 200 tries each and no refit. At t = 20 px the counted line missed the true angle by 1.19° on average; MSAC missed by 0.27°. At t = 3.9 px both were near 0.2°. MSAC costs nothing extra.
MLESAC goes one step further. It models each residual as Gaussian noise (an inlier) or spread evenly (an outlier), and scores a line by the likelihood of that mix. On synthetic fundamental matrices, Torr and Zisserman found MSAC and MLESAC beat RANSAC and least median of squares, with MLESAC slightly ahead at more cost.
Least median of squares (LMedS) needs no threshold: it keeps the line with the smallest median residual. But a median ignores only half the data, so its breakdown point is 50%. In our test with 40 pixels, LMedS held to 45% glare and failed past 55%; RANSAC with a known t held at 75%.
Symptom: with a generous threshold, RANSAC's answer drifts a degree or two between runs.
Measure: the residual spread inside the consensus set, not just its size.
Fix: score with MSAC (a one-line change), then refit.
Chapter 8
Rank the matches by how alike they look and watch the first clean sample arrive in a few tries
RANSAC draws every match with the same chance. But each match has a descriptor distance, and close matches are right more often. Chum and Matas (2005) used that. PROSAC, progressive sample consensus, sorts the matches by quality and draws first from the top few, then from a pool that grows. If the ranking is no better than chance, it ends up drawing like RANSAC.
A hundred matches, sorted by score, best at the left: green are right, red are wrong. Half are right. Slide how well the score predicts a right match, then press Race.
Illustrative: a right match scores its quality plus Gaussian noise, a wrong one noise alone. Samples of 7, as for F. We simplified PROSAC: the pool starts at the top 10 and grows by one match per try.
With a score quality of 1, our simplified PROSAC finds a clean 7-sample in a median of 3 tries; uniform RANSAC needs 124. With a useless score, PROSAC needs a median of 115 against 101: no help, a little worse early. The paper's own example, the Great Wall image pair: RANSAC tested 106,534 seven-match samples in 10.76 s, PROSAC 9 in 0.06 s, both finding 57 inliers. OpenCV's RHO method for homographies is PROSAC-based.
Two traps remain. A degenerate sample is clean but does not fix the model. Examples: two pixels side by side, three points on a line for a plane, eight matches on one flat wall for F. Check the sample's shape before you fit, or test whether a homography explains the inliers as well; for F that test is DEGENSAC (Chum, Werner and Matas, 2005).
The second trap is two structures, such as a wall and a floor. RANSAC returns the biggest group and treats the rest as outliers. To find both, remove the first group and run RANSAC again on what is left.
Symptom: a confident pose that is wrong, with a large consensus set that all lies on one wall.
Measure: how well a homography fits the inliers compared with F.
Fix: reject degenerate samples, compare H with F, and run RANSAC again on the leftover matches when the scene has two structures.
Chapter 9
Pour wrong matches into Lecture 7's street and watch RANSAC recover the turn the 8-point algorithm lost
Back to Lecture 7's toy street: camera 2 stands 0.6 m right and 0.8 m ahead and turned 10° left. Now add wrong matches, random pixel pairs, until they are a chosen share of all matches. The model is F, so the residual is the Sampson distance: a first-order estimate, in pixels, of how far a match must move to fit the epipolar geometry.
Each try runs the normalised 8-point algorithm on 8 random matches, counts matches within t of the result, and keeps the best. With local optimisation on, each new best is refit on its inliers until the count stops growing. At the end the page refits F, turns it into E with K, and picks the pose by the cheirality check of Lecture 7.
Left: each match drawn from its pixel in image 1 to its pixel in image 2. Right: top view, true camera 2 in blue and the recovered one in purple. Press Run; then add wrong matches, noise, or switch local optimisation off.
Illustrative toy street of Lecture 7: 37 right matches, K with f = 800 px, p = 0.99, a cap of 3,000 tries. OpenCV's findFundamentalMat (FM_RANSAC) and findEssentialMat (five-point RANSAC) recover the same turn within a degree on the same pixels.
At 40% wrong matches with 0.5 px of noise, the 8-point algorithm on all 62 matches reports a 24.0° turn: 55° of rotation error. RANSAC with local optimisation keeps 32 of the 37 right matches, takes in no wrong one, and recovers a 9.6° turn after 913 tries. Without local optimisation the same run needs 2,385 tries, because cramped 8-samples keep the vote low.
Push it. At 60% wrong matches the formula asks for 6,727 tries and the cap stops at 3,000. Raise the noise to 2 px with t at 1 px and good matches start failing the test. Set t to 6 px and wrong matches start to vote.
Chapter 10
Keep the formulas, the numbers and the code side by side
Least squares lets every datum vote with its squared residual, so one wrong match can own the answer. RANSAC asks a different question: which model do the most data agree with? It draws minimal samples, fits each, counts the data within t, keeps the best, and refits on the winners. The tries follow from w, s and p; the threshold follows from the noise.
| Piece | Formula | Number on this page | Watch out |
|---|---|---|---|
| Least squares | J = Σ ri2 | 1 glare pixel: 92% of J | breakdown point 0 |
| Vote | S = Σ 1[|ri| < t] | wrong line 2 to 5; right line 18 | ties at loose t |
| Clean sample | ws | w = 0.6: 0.36 (line) to 0.017 (8-point) | degenerate samples |
| Tries | N = log(1 − p) / log(1 − ws) | 72 (w 0.5, s 4); 1,177 (s 8) | w is unknown at first |
| Threshold | t2 = χ2m(0.95) σ2 | 1.96σ (line, F); 2.45σ (H) | units of the residual |
| Early stop | ŵ = |S*| / n | hero: 293 tries, then 21 | cramped samples |
| Refit | argmin Σi∈S* ri2 | 0.62° to 0.10° median error | recount after it |
| MSAC | C = Σ min(ri2, t2) | t = 20 px: 1.19° to 0.27° | not Huber |
| Residual for F | Sampson: (ũ2⊤Fũ1)2 / ((Fũ1)12 + (Fũ1)22 + (F⊤ũ2)12 + (F⊤ũ2)22) | t = 1 px at σ = 0.5 px | only the first two entries in the bottom |
python import math, numpy as np, cv2 def n_iters(w, s, p=0.99): # tries for confidence p if w >= 1: return 1 return math.ceil(math.log(1 - p) / math.log(1 - w**s)) def ransac(data, s, fit, resid, t, p=0.99, cap=2000, rng=np.random.default_rng(0)): n, best, budget, k = len(data), None, cap, 0 while k < budget: k += 1 model = fit(data[rng.choice(n, s, replace=False)]) # sample, fit inl = resid(model, data) < t # count if best is None or inl.sum() > best.sum(): # keep best = inl budget = min(cap, n_iters(inl.sum() / n, s, p)) # stop early for _ in range(5): # refit and recount model = fit(data[best]); inl = resid(model, data) < t if inl.sum() <= best.sum(): break best = inl return model, best # the library versions, on (N, 2) float pixel arrays p1, p2 and the 3x3 K H, m = cv2.findHomography(p1, p2, cv2.RANSAC, 2.5) # 4-point; threshold in px F, m = cv2.findFundamentalMat(p1, p2, cv2.FM_RANSAC, 1.0, 0.99) # 7-point inside E, m = cv2.findEssentialMat(p1, p2, K, cv2.RANSAC, 0.999, 1.0) # five-point inside n, R, t, m = cv2.recoverPose(E, p1, p2, K, mask=m) # cheirality on the inliers
We checked both the hand loop and the library calls on a synthetic homography: 100 matches, 40 of them wrong, 1 px of noise. Our 4-point loop stopped after 104 tries with 56 inliers, none wrong. cv2.findHomography kept 57, also none wrong; 55 matches were in both sets. Least squares on all 100 missed by a median of 138 px.
Lecture 6 produced matches, some wrong. Lecture 7 turned clean matches into a pose. This lecture finds the clean matches.
A visual odometry front end runs it on every frame. The inlier ratio itself is a health signal: a sudden drop points to blur, a texture-poor view or a matcher failure. Lecture 9 then refines poses and points together by nonlinear least squares, on the inliers RANSAC kept. Lecture 14 returns to outliers, this time in whole SLAM back ends.
Now press Present or Teach. Show why one wrong pixel owns a least-squares fit. Derive N from (1 − ws)N = 1 − p and work w = 0.5, s = 4. Set t from σ with the chi-square value, and explain the refit and LO-RANSAC. Then go back to the hero and say why least squares tilts to 16.8° while RANSAC stays at 25°.