Exercise: RANSAC

Goal

By the end of this exercise you should be able to:

  • run a few RANSAC iterations by hand: fit a minimal sample, count inliers, choose,
  • compute the number of iterations for a given inlier fraction and sample size,
  • choose \varepsilon and predict what goes wrong when it is too small or too large,
  • decide between voting (Hough) and hypothesise-and-verify (RANSAC) for a problem,
  • (math) derive the iteration formula and the least-squares refits for lines and circles.

Do the pen-and-paper part first, then the demo.

Background

Idea What it means
Minimal sample the fewest points that determine the model: s = 2 (line), 3 (circle), 3 pairs (affine transform)
Inliers points within distance \varepsilon of the model
RANSAC repeat N times: sample, fit exactly, count inliers; keep the best; refit on its inliers
Success probability P = 1 - (1 - w^s)^N, w = inlier fraction
Iterations N = \log(1 - p)/\log(1 - w^s), rounded up
Line distance |x\cos\theta + y\sin\theta - \rho| for a line in normal form

By hand

B1. Eight points: (0, 0), (1, 1), (2, 2), (3, 3), (4, 4.2), (5, 1), (1, 4), (4, 0). Use \varepsilon = 0.5. (a) Sample 1 is \{(0, 0), (3, 3)\}. Give the line through them in normal form and the distance of every point to it. How many inliers? (b) Sample 2 is \{(5, 1), (1, 4)\}. Show that the line through them is 3x + 4y = 19, i.e. normal (0.6, 0.8) and \rho = 3.8. Distances and inliers? (c) Which model does RANSAC keep? Which points are used in the refit, and roughly where will the refitted line be?

B2. Iterations for a 99 % chance of at least one all-inlier sample: (a) a line with w = 0.5; (b) a circle with w = 0.5; (c) a line with w = 0.2; (d) a circle with w = 0.3. (e) With w = 0.2 and only the 17 iterations of (a), what is the chance of success?

B3. Voting or guessing? Explain your choice. (a) A single straight filament in an image where 90 % of the edge points are clutter. (b) Fitting an affine transform (6 parameters, 3 point pairs per sample) to matched points of two images, with 40 % wrong matches. (c) Finding all 20 straight edges of a building facade.

B4. The inliers of a line scatter with a standard deviation of 0.8 px. (a) Suggest \varepsilon. (b) A second line runs parallel, 8 px away. What is the largest \varepsilon that keeps the two lines apart, and what happens above it?

B1. (a) The line y = x: normal (\cos 135°, \sin 135°) = (-0.707, 0.707), \rho = 0 (any sign convention: distance |x - y|/\sqrt2). Distances: 0, 0, 0, 0, 0.14, 2.83, 2.12, 2.83. 5 inliers: the first five points. (b) The direction from (5, 1) to (1, 4) is (-4, 3), so the normal is (3, 4)/5 = (0.6, 0.8); \rho = 0.6 \cdot 5 + 0.8 \cdot 1 = 3.8, i.e. 3x + 4y = 19. Distances |3x + 4y - 19|/5: 3.8, 2.4, 1.0, 0.4, 1.96, 0, 0, 1.4. 3 inliers: (3, 3), (5, 1), (1, 4). (c) Sample 1 (5 inliers). The refit uses (0, 0), (1, 1), (2, 2), (3, 3), (4, 4.2): the total-least-squares line through their centroid (2, 2.04), at about 46.1° (slightly steeper than 45°, pulled by (4, 4.2)). The three outliers play no part.

B2. (a) \log 0.01/\log(1 - 0.25) = 16.0: 17. (b) \log 0.01/\log(1 - 0.125) = 34.5: 35. (c) \log 0.01/\log(1 - 0.04) = 112.8: 113. (d) w^3 = 0.027: \log 0.01/\log 0.973 = 168.2: 169. (e) 1 - 0.96^{17} = 0.50: a coin toss.

B3. (a) Hough. RANSAC with w = 0.1, s = 2 needs \log 0.01/\log 0.99 = 459 samples; the Hough transform with gradient voting handles a 90 % clutter fraction with a fixed amount of work, as long as the filament’s peak stands above the floor. (b) RANSAC: w = 0.6, s = 3: \log 0.01/\log(1 - 0.216) = 19 samples; a 6D accumulator with 20 steps per parameter has 20^6 = 64 million cells. (c) Hough: 20 instances of a 2-parameter model, all found in one pass; RANSAC would need 20 sequential runs, the first ones with a small inlier fraction (w \approx 1/20 per line among the edge points).

B4. (a) 2 to 3 times the noise: \varepsilon \approx 2 px (the demo uses 2). (b) A model halfway between the lines is 4 px from each; with \varepsilon \ge 4 its band contains both lines, so it beats each true line and the two merge. Keep \varepsilon well below 4 (2 is fine).

Math questions

B5. (math) Derive N = \log(1 - p)/\log(1 - w^s). Show that for small w^s, N \approx 4.6/w^s when p = 0.99. By what factor does N grow when w halves, for a line and for a circle?

B6. (math) Show that the total-least-squares line (minimising the sum of squared perpendicular distances) passes through the centroid and that its normal is the eigenvector of the scatter matrix S with the smaller eigenvalue. Check with B1(c): the five inliers have centroid (2, 2.04); is the refitted line close to y = x?

B7. (math) Write the algebraic circle fit as a linear least-squares problem in (a, b, c) with c = r^2 - a^2 - b^2. Set up the system for the four points (5, 0), (0, 5), (-5, 0), (0, -5) and solve it. What quantity does the algebraic fit minimise, and why is it not exactly the geometric distance?

B5. A sample is all-inlier with probability w^s; samples are independent, so all N fail with probability (1 - w^s)^N. Requiring (1 - w^s)^N \le 1 - p and taking logarithms (both negative, so the inequality flips when dividing): N \ge \log(1 - p)/\log(1 - w^s). For small q = w^s, \log(1 - q) \approx -q, so N \approx -\log(0.01)/q = 4.6/w^s. Halving w multiplies w^s by 2^{-s}, so N grows about 4 times for a line and 8 times for a circle.

B6. \partial/\partial\rho \sum_i(\mathbf n^\top\mathbf p_i - \rho)^2 = -2\sum_i(\mathbf n^\top\mathbf p_i - \rho) = 0 gives \rho = \mathbf n^\top\bar{\mathbf p}. The remaining cost is \mathbf n^\top S\,\mathbf n with S = \sum_i(\mathbf p_i - \bar{\mathbf p})(\mathbf p_i - \bar{\mathbf p})^\top; over unit vectors its minimum is the smallest eigenvalue, attained at its eigenvector (Rayleigh quotient). For B1(c): the deviations from the centroid are (-2, -2.04), (-1, -1.04), (0, -0.04), (1, 0.96), (2, 2.16); S has a dominant eigenvector at 46.1° and the normal at 136.1°: close to y = x, tilted by 1.1° towards (4, 4.2).

B7. (x - a)^2 + (y - b)^2 = r^2 \iff x^2 + y^2 = 2ax + 2by + c. Each point gives one row: [2x_i \;\; 2y_i \;\; 1]\,(a, b, c)^\top = x_i^2 + y_i^2. For the four points: rows (10, 0, 1), (0, 10, 1), (-10, 0, 1), (0, -10, 1), right-hand side 25 each. The normal equations A^\top A = \operatorname{diag}(200, 200, 4), A^\top \mathbf z = (0, 0, 100) give a = b = 0, c = 25, r = \sqrt{25} = 5. The fit minimises \sum_i (x_i^2 + y_i^2 - 2ax_i - 2by_i - c)^2 = \sum_i (d_i^2 - r^2)^2 = \sum_i (d_i - r)^2(d_i + r)^2, with d_i the distance of point i from the centre: the geometric error (d_i - r) weighted by (d_i + r)^2, so points outside the circle count more than points inside. For exact or nearly exact data it agrees with the geometric fit; it is linear and needs no starting guess.

Explore

The point set: inliers on a line (or a circle) with noise of 0.8 px, plus uniform outliers, all from a fixed seed. Click to add a point, click a point to remove it, drag to move it. One sample draws a minimal sample (red, with its band of ±\varepsilon) and counts its inliers; run all finishes the iterations and shows the best model refitted on its inliers (blue; green points are its inliers). Orange, dashed: least squares on all points. Top right: the inlier count of each sample (bars) and the best so far (blue). Middle right: the chance of at least one all-inlier sample against N, with the current iteration (red dot) and the 99 % value. Optional: a second model (sequential RANSAC, purple) and the line Hough accumulator of the same points (its peak drawn purple, dotted).

R1. Preset least squares fails (30 % outliers). The true line is \theta = 63°, \rho = 58. What does least squares on all points give? Press run all: what does RANSAC give, with how many inliers, and how many of them are true inliers?

R2. Preset RANSAC: 17 iterations (w = 0.5). Press restart, then one sample 17 times. Which samples are all-inlier (the readout says so), how many inliers do they get, and which one becomes the best? Compare the refit with least squares.

R3. Still on that preset, try seeds 1 to 10. In how many runs is the refitted line right? Is that consistent with the 99 % on the curve?

R4. Preset 80 % outliers (100 points, 17 iterations, Hough accumulator on). What is the chance of success after 17 samples? What does RANSAC find with seed 1, and what does the Hough transform find? Now set the iterations to 113. What changes? Look at the all-inlier samples in the readout as you step: why do some of them get only a few inliers?

R5. Preset ε too large: two lines merge (two parallel lines 8 px apart, \varepsilon = 6). Where is the RANSAC line, and how many inliers does it have? Set \varepsilon = 2.

R6. Preset two lines: sequential. What does least squares give? What do the first and the second RANSAC model give? Compare with the true lines \theta = 131.8°, \rho = -10 and \theta = 71.6°, \rho = 62.

R7. Preset circle (true centre (52, 48), r = 28). How many iterations are needed for 99 %? Compare the RANSAC refit with the least-squares circle on all points. Which parameter does least squares get most wrong, and why?

R8. Back to RANSAC: 17 iterations, set \varepsilon = 0.5. What happens to the inlier counts and the refit? Why?

R1. Least squares: \theta = 68.6°, \rho = 59.1, visibly tilted by the outliers. RANSAC (refit): \theta = 62.9°, \rho = 58.0, with 41 inliers, all of them true inliers (42 points are on the line).

R2. Samples 2, 3 and 14 are all-inlier, with 29, 29 and 30 inliers; the best is sample 14 (30). Mixed samples get 3 to 16. The refit uses 31 inliers (29 true, 2 outliers that happen to lie within 2 px): \theta = 63.4°, \rho = 58.1, against \theta = 75.8°, \rho = 56.4 for least squares.

R3. In all ten runs at least one sample is all-inlier, and the refit lands within about 1° of 63° and 0.3 of 58 (for example seed 4: the very first sample is all-inlier). That fits 99 %: a failure is expected in about 1 run in 100.

R4. 50 % (1 - 0.96^{17}). With seed 1 no sample is all-inlier; the best is a chance alignment of 10 points (4 true inliers) at \theta = 85.9°, \rho = 53.2: wrong. The Hough peak is at \theta = 63°, \rho = 58.2 with 22 votes: right. With 113 iterations the best model appears at iteration 18 (22 inliers), and the refit is \theta = 62.1°, \rho = 58.7 with 24 inliers (18 true). The all-inlier samples (iterations 91 and 93) get only 8 and 7 inliers: their two points are close together, so the noise of 0.8 px tilts the line through them a lot. A sample with a long baseline (even one containing an outlier that happens to lie near the line, as at iteration 18) fits better.

R5. The refit is \theta = 74.1°, \rho = 54.6, with 42 inliers: halfway between the two lines (\rho = 50 and 58), with both inside its band. With \varepsilon = 2: \theta = 76.4°, \rho = 50.9, 24 inliers, all true: one of the two lines.

R6. Least squares: \theta = 163.1°, \rho = -28.9, a line that fits neither. First model: \theta = 131.8°, \rho = -10.2 (21 inliers); second, after removing those: \theta = 71.4°, \rho = 62.2 (21 inliers). Both match the true lines.

R7. 35 iterations (s = 3, w = 0.5). RANSAC refit: centre (51.8, 48.4), r = 27.8. Least squares on all points: centre (51.5, 48.2) but r = 34.8. The outliers are spread evenly around the circle, so they barely move the centre, but on average they lie farther out than the circle, so the radius grows.

R8. With \varepsilon = 0.5 (smaller than the noise of 0.8) most true inliers fall outside the band: the best model has only 10 inliers (9 true), and the refit \theta = 64.4°, \rho = 58.2 rests on few points. The counts are small and noisy, so the choice of the best model is close to chance. \varepsilon should be 2 to 3 times the noise.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in hough/src/ransac/exercise.rs. A line is in normal form x\cos\theta + y\sin\theta = \rho with \theta in [0°, 180°), as in the line unit (in the code \theta is in radians and y points down).

C1. line_through(p, q) and distance(line, p): the normal is perpendicular to \mathbf q - \mathbf p, scaled to length 1, and \rho = \mathbf n \cdot \mathbf p; the distance is |x\cos\theta + y\sin\theta - \rho|. The checks are B1 (a) and (b).

C2. iterations_needed(w, s, p): N = \log(1 - p)/\log(1 - w^s), rounded up. The check is B2.

C3. fit_line_tls(points): the refit by total least squares (B6):

(x̄, ȳ) = the centroid of the points
sxx, sxy, syy = sums of (x − x̄)², (x − x̄)(y − ȳ), (y − ȳ)²
α = ½ atan2(2 sxy, sxx − syy)              # direction of largest spread
normal = (−sin α, cos α);   the line passes through (x̄, ȳ)

The check is B6: the five inliers of B1 give a normal at 136.1°.

C4. ransac_line(points, eps, iterations, rng): the loop of the lecture, with two different random points per sample, and the refit with C3 on the inliers of the best sample. The checks: B1 (c), and a line with 50 % outliers.

C5. fit_circle(points): the algebraic fit of B7, a linear least-squares problem in (a, b, c) (the library’s least_squares solves it). It also gives the circle through a minimal sample of three points. The checks are B7 and three points of a known circle.

Then cargo run -p hough -- ransac. It fits a line (\theta = 63°, \rho = 58, 30 points with noise 0.8 and 30 outliers in a 100 \times 100 square) by least squares on all points and by RANSAC with 17 samples; repeats RANSAC on 1 000 new data sets for three settings and counts how often it finds the line; and fits a circle (centre (52, 48), r = 28, 30 points and 30 outliers) both ways. out/ransac/line.png and circle.png show the points (green = inliers of RANSAC), RANSAC (blue) and least squares (orange, dashed).

C6. Compare least squares and RANSAC for the line and for the circle. Which parameter of the circle does least squares get most wrong, and why?

C7. Compare the measured success rates with the predicted chance of at least one all-inlier sample. Why is the measured rate a little lower when w = 0.2 and N = 113?

C8. (math) RANSAC’s cost is N times the number of points (one distance per point and sample). With w = 0.2, how does N change for a line (s = 2) and for a homography (s = 4)? Use the approximation N \approx 4.6/w^s of B5.

The model solution is hough/src/ransac/solution.rs in the download.

C6. Line: least squares on all points (perpendicular distances) gives \theta = 65.0°, \rho = 60.2, pulled towards the outliers; RANSAC with 17 samples gives \theta = 63.3°, \rho = 58.0 with 33 inliers, all 30 line points among them (and 3 outliers that happen to lie within 2 px). Circle: least squares gives centre (50.2, 44.0) and r = 32.5; RANSAC with 35 samples gives (52.2, 48.2), r = 28.2, with 30 inliers. The radius is worst: the outliers lie all around, inside and outside, so they shift the centre only a little, but on average they lie farther from the centre than the circle does, which inflates the radius (as in demo question R7).

C7. w = 0.5, 17 samples: 98.3 % found, predicted 99.2 %. w = 0.2, 17 samples: 49.1 % against 50.0 %: a coin toss. w = 0.2, 113 samples: 97.5 % against 99.0 %. The formula counts the chance of an all-inlier sample, but not every all-inlier sample gives a good line: two inliers close together, with noise of 0.8 px, give a badly tilted line with few inliers, and then a chance alignment of outliers can win (demo question R4). With more outliers this matters more.

C8. Line: 4.6/0.2^2 = 115 (exactly 113). Homography: 4.6/0.2^4 = 2\,875 samples (2 876 with the exact formula). With s = 4 every halving of w multiplies N by 16; for small inlier fractions RANSAC becomes expensive, and voting, or a better guess of which points match, is needed.

Where this leads

RANSAC returns the best model and its inliers; with matched feature points between two images the same loop estimates the transform that aligns them: the keypoints day (day 24), and for two camera views geometry from multiple images (day 53). The other days of Part IV take a different route to finding objects: integral images make box filters so cheap that a detector can test millions of windows.