v9.1.1
Menu

RANSAC Line Fit

hardFREERANSACRobust EstimationCV: Model Fitting and Optimization

Implement a RANSAC algorithm to fit a line to a set of points. The goal is to find the best line that represents the majority of the points, despite the presence of outliers.

The RANSAC algorithm is a model fitting technique that uses a random sampling approach to find the best model. It is based on the idea of selecting a random subset of points, fitting a model to these points, and then checking how well this model fits the rest of the points.

  1. Select a random subset of 2 points
  2. Fit a line to these points using the equation y=mx+by = mx + b
  3. Count the number of inliers, points that are close to the fitted line: a point (x,y)(x, y) is an inlier when its perpendicular distance ∣mx−y+b∣m2+1\frac{|mx - y + b|}{\sqrt{m^2 + 1}} is strictly less than threshold
  4. Repeat the process for a specified number of iterations, keeping the line with the most inliers (a later line replaces it only if it has strictly more)

Seed the random number generator with seed before sampling. Skip any sampled pair with equal xx coordinates (a vertical line has no slope mm).

y=mx+by = mx + b

This technique is widely used in computer vision for tasks such as line detection and image registration.

Example

Input
ransac_line([(0,0), (1,1), (2,2), (1,5)], 100, 0.5, 42)
Output
[1.0, 0.0]
Reasoning
  • points are four (x,y)(x, y) positions; iterations = 100 random draws, threshold = 0.5 is the inlier distance and seed = 42 makes the draws repeatable.
  • A pair fixes a line: m=y2−y1x2−x1m = \frac{y_2 - y_1}{x_2 - x_1}, b=y1−mx1b = y_1 - m x_1. For (0,0)(0,0) and (2,2)(2,2): m=2/2=1m = 2/2 = 1, b=0b = 0, i.e. y=xy = x.
  • Distances to y=xy = x are ∣x−y∣2\frac{|x - y|}{\sqrt{2}}: 00 for the three diagonal points and 4/2≈2.8284/\sqrt{2} \approx 2.828 for (1,5)(1,5), so 3 inliers.
  • A line through the outlier does worse: (0,0),(1,5)(0,0),(1,5) gives y=5xy = 5x, where (1,1)(1,1) is 4/26≈0.7844/\sqrt{26} \approx 0.784 away, above 0.50.5, so only 2 inliers. (2,2),(1,5)(2,2),(1,5) gives y=−3x+8y = -3x + 8, also 2. The pair (1,1),(1,5)(1,1),(1,5) is vertical and is skipped.
  • Of the 6 possible pairs, 3 produce y=xy = x, so 100 draws certainly hit it and nothing beats 3 inliers: output [1.0, 0.0]. Notice the outlier never moves the answer, which is the point of RANSAC.

Constraints

  • iterations: number of RANSAC iterations
  • threshold: inlier threshold
  • Return best [m, b] rounded to 4 decimal places

More from CV: Model Fitting and Optimization

solution.py

Test results

Sign in to run your code against the test cases.