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

Points [0,0], [1,1], [2,2] and [3,3] lie on the line y=xy = x, i.e. x−y=0x - y = 0. Normalising the normal vector to unit length gives 0.7071x−0.7071y+0=00.7071x - 0.7071y + 0 = 0.

Point [10,0] is 10/2≈7.0710/\sqrt{2} \approx 7.07 away from that line, far beyond the 0.1 threshold, so it's an outlier. RANSAC keeps the line with the most inliers: 4.

Note: a line has two equally valid unit normals, (a,b,c)(a, b, c) and (−a,−b,−c)(-a, -b, -c). Which one you get depends on the order of the two points RANSAC happened to sample, so [−0.7071,0.7071,0.0][-0.7071, 0.7071, 0.0] is the same line. (-0.0 is just how Python prints 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.