v9.1.1
Menu

Line from Two Points

Implement a function to compute the parameters of a line given two points. The concept of fitting a line to a set of points is fundamental in Model Fitting and Optimization, particularly in the context of RANSAC, where it's used to robustly estimate the parameters of a model from noisy data.

To find the line parameters, we can use the slope-intercept form of a line, y=mx+by = mx + b, where mm is the slope and bb is the y-intercept. Given two points (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2), we can calculate the slope mm as the ratio of the difference in yy-coordinates to the difference in xx-coordinates.

  1. Calculate the difference in yy-coordinates and xx-coordinates between the two points.
  2. Compute the slope mm using the differences calculated in step 1.
  3. Use one of the points to solve for the y-intercept bb.
m=y2−y1x2−x1,b=y1−m⋅x1m = \frac{y_2 - y_1}{x_2 - x_1}, \quad b = y_1 - m \cdot x_1

This technique is widely used in computer vision applications, such as line detection in images.

Example

Input
line_from_points((0,0), (2,4))
Output
[2.0, 0.0]
Reasoning
  • The inputs p1 = (0,0) and p2 = (2,4) are two points on the line, each written as (x,y)(x, y): so x1=0,y1=0x_1 = 0, y_1 = 0 and x2=2,y2=4x_2 = 2, y_2 = 4.
  • Slope: moving from the first point to the second, xx rises by Δx=2−0=2\Delta x = 2 - 0 = 2 while yy rises by Δy=4−0=4\Delta y = 4 - 0 = 4. The slope is rise over run, m=42=2.0m = \frac{4}{2} = 2.0, so each unit step in xx adds 2 to yy.
  • Intercept: the line must pass through (x1,y1)(x_1, y_1), so 0=2.0⋅0+b0 = 2.0 \cdot 0 + b, giving b=0.0b = 0.0. Checking with the other point: 2.0⋅2+0.0=42.0 \cdot 2 + 0.0 = 4, as required.
  • Output: the pair [m,b][m, b] = [2.0, 0.0], i.e. the line y=2xy = 2x, with both values as decimals rounded to 4 decimal places.
  • Notice that swapping the two points flips the signs of both Δy\Delta y and Δx\Delta x, so the slope (and the line) is unchanged.

Constraints

  • Assume x1 ≠ x2 (non-vertical line)
  • Return [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.