v9.1.1
Menu

RANSAC Line Fitting

Implement RANSAC for robust line fitting to 2D points with outliers. This task involves using the RANSAC algorithm to estimate the parameters of a line that best fits a set of 2D points, some of which may be outliers.

The RANSAC algorithm is a robust estimation technique used to fit models to data with outliers. It works by randomly selecting a minimum number of samples, fitting a model to these samples, and then counting the number of inliers, which are points that are within a certain threshold of the model. The process is repeated for a specified number of iterations, and the model with the most inliers is kept as the best fit. In the case of line fitting, the line can be represented by the equation ax+by+c=0ax + by + c = 0, where a2+b2=1a^2 + b^2 = 1. The distance from a point (x0,y0)(x_0, y_0) to the line is given by d=∣ax0+by0+c∣d = |ax_0 + by_0 + c|.

Here are the steps to follow:

  1. Randomly select a minimum number of samples (2 points for a line)
  2. Fit a line to these samples
  3. Count the number of inliers (points within a threshold of the line)
  4. Repeat for a specified number of iterations
d=∣ax0+by0+c∣d = |ax_0 + by_0 + c|

This technique is widely used in computer vision applications, such as image processing and feature detection.

Example

Input
points = [[0,0], [1,1], [2,2], [3,3], [10,0]]  # Last is outlier
threshold = 0.1
n_iterations = 100
Output
{'line': [0.7071, -0.7071, -0.0], 'inliers': 4}
Reasoning
  • Inputs: five 2D points, an inlier threshold of 0.1 (a perpendicular distance), and 100 trials, each taking the line through a random pair of points as a candidate.
  • A good pair: any two of [0,0], [1,1], [2,2], [3,3] give the line x−y=0x - y = 0. Its normal (1,−1)(1, -1) has length 2\sqrt{2}, so scaling to unit length gives a=0.7071a = 0.7071, b=−0.7071b = -0.7071, c=0c = 0.
  • Scoring it: the four diagonal points have d=0d = 0. For [10,0], d=∣0.7071⋅10−0.7071⋅0∣≈7.07d = |0.7071 \cdot 10 - 0.7071 \cdot 0| \approx 7.07, far above 0.1. Score: 4 inliers.
  • A bad pair: [0,0] with [10,0] gives the line y=0y = 0, which passes through only those 2 points. Score: 2. Since 6 of the 10 possible pairs are good, 100 trials almost surely find the best line.
  • Output: line is rounded to 4 decimal places and inliers is 4. Notice that (a,b,c)(a, b, c) and (−a,−b,−c)(-a, -b, -c) are the same line, so (−0.7071,0.7071,0)(-0.7071, 0.7071, 0) is equally correct; -0.0 is a rounded negative zero.

Constraints

  • points: List of [x, y] coordinates
  • threshold: Max distance to be considered inlier
  • n_iterations: Number of RANSAC iterations
  • Return: Dict with 'line' [a,b,c] and 'inliers' count

Learn this in

More from CV: Model Fitting and Optimization

solution.py

Test results

Sign in to run your code against the test cases.