Algorithm Search⌘K

Algorithmintro

RANSAC

Also called random sample consensus.

Fit a model to many random minimal samples of the data, count the data within a threshold of each model, and keep the model with the largest consensus set.

Time
Θ(k n) worst · average · best
Space
Θ(n) extra
Where
k = the number of samples drawn, at most a set cap; n = the number of data items; s = the size of a minimal sample
Properties
randomizednot exactofflineiterative
Origin
Martin A. Fischler, Robert C. Bolles, 1981

RANSAC (random sample consensus) is a randomized method to fit a model to data in which a large part of the items are wrong. It draws a random minimal sample, the smallest set of items that fixes the model (2 points for a line, 4 point matches for a homography), fits the model to the sample, and counts the items whose error is at most a threshold ε\varepsilon. These items form the consensus set of the model. After many samples, RANSAC keeps the model with the largest consensus set and usually refits it to that set by least squares. Unlike ordinary least squares, whose answer one bad item can move arbitrarily far, RANSAC can tolerate more than half of the data being outliers, because a model is judged only by the items that agree with it. It is the standard tool of robust model fitting in computer vision.

In plain words

You have a cloud of dots. Most of them lie close to one straight line, but many are scattered at random. You want the line. A line fit to all dots is pulled away by the scattered ones.

So you guess. Pick two dots at random and draw the line through them. Count how many dots lie close to that line. If both picked dots were on the true line, the count is large. If one of them was a stray dot, the count is usually small. Repeat many times and keep the line with the largest count.

How many times is enough? If half the dots are good, two random dots are both good about one time in four. Seventeen tries then find a good pair with a chance of 99 in 100. At the end, refit the line to all the dots that agreed with the best guess.

The problem

The input is a set D={x1,…,xn}D = \{x_1, \ldots, x_n\} of data items, a model class with a solver that fits a model θ\theta to a minimal sample of ss items, a residual r(θ,x)≥0r(\theta, x) \ge 0, an inlier threshold ε>0\varepsilon > 0, a confidence p∈(0,1)p \in (0, 1) and a cap kmax⁡k_{\max} on the number of samples. The consensus set of a model is I(θ)={x∈D:r(θ,x)≤ε}I(\theta) = \{x \in D : r(\theta, x) \le \varepsilon\}. The output is a model with a large consensus set, and that set. The exact goal, a model with the largest consensus set, is maximum consensus; it is NP-hard in general (see robust model fitting), and RANSAC is a randomized heuristic for it with a probabilistic guarantee under stated assumptions.

The algorithm

  1. RANSAC(D, s, ε, p, k_max) ▷ n = |D|
  2. 1θ* ← none, I* ← ∅, k ← k_max, t ← 0
  3. 2while t < k do
  4. 3t ← t + 1
  5. 4S ← s distinct items of D, drawn uniformly at random
  6. 5θ ← FIT-MINIMAL(S) ▷ none for a degenerate sample
  7. 6if θ is none then continue
  8. 7I ← {x ∈ D : r(θ, x) ≤ ε}
  9. 8if |I| > |I*| then
  10. 9θ* ← θ, I* ← I
  11. 10w ← |I*| / n
  12. 11k ← min(k_max, ⌈log(1 − p) / log(1 − w^s)⌉)
  13. 12if θ* is none then return failure
  14. 13θ ← FIT-LEAST-SQUARES(I*)
  15. 14return θ, I*

Lines L4 to L7 are one hypothesize and verify round: a model from a sample, then its consensus set over all the data. Lines L10 and L11 are the adaptive stopping rule of Hartley and Zisserman (Section 4.7). The inlier ratio ww is not known in advance, so the rule uses the ratio of the best consensus set found so far. This estimate only grows, so kk only shrinks. The count in line L11 is the RANSAC iteration bound. When ws=1w^s = 1, all items agree with the model, and the code stops at once. Line L13 is the final step of Fischler and Bolles: a least squares fit to the whole consensus set, which averages the noise of all inliers instead of the noise of ss items.

The threshold ε\varepsilon is a design choice. For a residual of one dimension with Gaussian noise of standard deviation σ\sigma, a common choice is ε2=3.84 σ2\varepsilon^2 = 3.84\,\sigma^2, the 95 percent point of a chi-square variable with one degree of freedom (Hartley and Zisserman, Section 4.7); it is tuned in practice.

Example

Take the 8 points (0,0),(1,1),(2,2),(3,3),(4,4),(0,4),(1,3),(4,0)(0,0), (1,1), (2,2), (3,3), (4,4), (0,4), (1,3), (4,0), a line model with s=2s = 2, the point-to-line distance as the residual, ε=0.1\varepsilon = 0.1 and p=0.99p = 0.99. Five points lie on y=xy = x. Four points, (0,4),(1,3),(2,2),(4,0)(0,4), (1,3), (2,2), (4,0), lie on x+y=4x + y = 4; the point (2,2)(2,2) is on both lines.

tt sample line consensus set ∣I∗∣\lvert I^*\rvert ww kk
0 0 kmax⁡k_{\max}
1 (0,4),(4,0)(0,4), (4,0) x+y=4x + y = 4 (0,4),(1,3),(2,2),(4,0)(0,4), (1,3), (2,2), (4,0) 4 1/21/2 17
2 (1,1),(1,3)(1,1), (1,3) x=1x = 1 (1,1),(1,3)(1,1), (1,3) 4 17
3 (0,0),(3,3)(0,0), (3,3) y=xy = x the five points on y=xy = x 5 5/85/8 10

After row 1, ⌈log⁡0.01/log⁡(1−0.25)⌉=⌈16.01⌉=17\lceil \log 0.01 / \log(1 - 0.25) \rceil = \lceil 16.01 \rceil = 17. After row 3, w2=0.390625w^2 = 0.390625 and ⌈log⁡0.01/log⁡0.609375⌉=⌈9.30⌉=10\lceil \log 0.01 / \log 0.609375 \rceil = \lceil 9.30 \rceil = 10. The samples of rounds 4 to 10 can only tie or lose, so the loop stops at t=10t = 10 and line L13 refits y=xy = x to its five points. The second structure, x+y=4x + y = 4, is a strong competitor: if the threshold were larger or the data noisier, the two counts could swap. Fitting several lines at once is the task of J-linkage.

Correctness

RANSAC keeps an invariant at line L2: I∗I^* is the largest consensus set among the models of the samples drawn so far, and θ∗\theta^* is its model. The loop ends, because tt grows by 1 in each round and k≤kmax⁡k \le k_{\max}. The guarantee is probabilistic. Let II be a largest consensus set, let qq be the probability that a random sample lies inside II, and assume that each sample inside II gives a model whose consensus set has size ∣I∣|I|. If q≥(∣I∣/n)sq \ge (|I|/n)^s and kmax⁡≥⌈log⁡(1−p)/log⁡(1−q)⌉k_{\max} \ge \lceil \log(1 - p) / \log(1 - q) \rceil, the run returns a consensus set of the largest size with probability at least pp. The proof shows that the adaptive rule never stops before this count, because the estimate ww never exceeds ∣I∣/n|I|/n. For samples drawn with replacement, q=(∣I∣/n)sq = (|I|/n)^s exactly. For distinct items, q=(∣I∣s)/(ns)q = \binom{|I|}{s} / \binom{n}{s}, which is a little smaller, so the rule of line L11 is slightly optimistic for small nn. The full proof is below.

Proof: RANSAC keeps the largest consensus set it sees and finds a largest one with probability p under the sampling assumptionsfull

We use the notation of the page. DD has nn items, a minimal sample has s≤ns \le n distinct items, and I(θ)={x∈D:r(θ,x)≤ε}I(\theta) = \{x \in D : r(\theta, x) \le \varepsilon\} is the consensus set of a model θ\theta. Let m∗m^* be the largest ∣I(θ)∣|I(\theta)| over the models that the minimal solver can return from some sample, and let II be a consensus set of size m∗m^*. Let qq be the probability that one sample of line L4 is a subset of II, and let k(w)=⌈log⁡(1−p)/log⁡(1−ws)⌉k(w) = \lceil \log(1 - p) / \log(1 - w^s) \rceil for 0<w<10 < w < 1, with k(1)=1k(1) = 1. The minimal solver, the residual and the refit are correct subroutines, and the model of computation is the real RAM.

Claim. (a) At each test of line L2, I∗I^* is a consensus set of largest size among the models of the samples drawn so far, and θ∗\theta^* is its model. (b) The loop ends after at most kmax⁡k_{\max} rounds. (c) Assume that the samples are independent, that every sample inside II gives a model whose consensus set has size m∗m^*, that q≥(m∗/n)sq \ge (m^*/n)^s and that kmax⁡≥⌈log⁡(1−p)/log⁡(1−q)⌉k_{\max} \ge \lceil \log(1 - p) / \log(1 - q) \rceil. Then the set I∗I^* returned in line L14 has size m∗m^* with probability at least pp.

Lemma 1 (invariant). Part (a) holds.

Proof. Before the first round no sample is drawn and I∗=∅I^* = \emptyset. In a round, either line L6 skips the sample, so the set of models does not change, or line L7 computes I(θ)I(\theta) for the new model θ\theta. Line L8 replaces I∗I^* exactly when ∣I(θ)∣>∣I∗∣|I(\theta)| > |I^*|, so after line L9, I∗I^* has the largest size among the old models and the new one. □\square

Lemma 2 (termination). Part (b) holds.

Proof. kk starts at kmax⁡k_{\max}, and line L11 sets it only to values at most kmax⁡k_{\max}. Each round increases tt by 1, so after kmax⁡k_{\max} rounds t≥kmax⁡≥kt \ge k_{\max} \ge k and the test of line L2 fails. □\square

Lemma 3 (the adaptive count does not stop too early). At each test of line L2, k≥min⁡(kmax⁡,k(m∗/n))k \ge \min(k_{\max}, k(m^*/n)).

Proof. For 0<w<10 < w < 1, log⁡(1−ws)\log(1 - w^s) is negative and decreases as ww grows, so log⁡(1−p)/log⁡(1−ws)\log(1 - p) / \log(1 - w^s) is positive and does not increase; hence k(w)k(w) does not increase in ww. By Lemma 1, ∣I∗∣≤m∗|I^*| \le m^* at all times, so the value w=∣I∗∣/nw = |I^*|/n of line L10 is at most m∗/nm^*/n, and line L11 sets k=min⁡(kmax⁡,k(w))≥min⁡(kmax⁡,k(m∗/n))k = \min(k_{\max}, k(w)) \ge \min(k_{\max}, k(m^*/n)). Before the first update, k=kmax⁡k = k_{\max}. □\square

Proof of (c). Let K=⌈log⁡(1−p)/log⁡(1−q)⌉K = \lceil \log(1 - p) / \log(1 - q) \rceil. From q≥(m∗/n)sq \ge (m^*/n)^s we get K≤k(m∗/n)K \le k(m^*/n), and K≤kmax⁡K \le k_{\max} by assumption. By Lemma 3, the loop does not stop before round KK unless ∣I∗∣=m∗|I^*| = m^* already. The samples are independent, so the probability that none of the first KK samples is a subset of II is (1−q)K≤1−p(1 - q)^K \le 1 - p, by the choice of KK. If one of them is a subset of II, its model has a consensus set of size m∗m^* by assumption, and by Lemma 1 I∗I^* has size m∗m^* from that round on. Line L13 changes the model but not I∗I^*, and line L14 returns I∗I^*. □\square

Remark (sampling without replacement). If the ss items of a sample were drawn with replacement, q=(m∗/n)sq = (m^*/n)^s and the condition q≥(m∗/n)sq \ge (m^*/n)^s holds with equality. Line L4 draws ss distinct items, so q=(m∗s)/(ns)=∏j=0s−1m∗−jn−jq = \binom{m^*}{s} / \binom{n}{s} = \prod_{j=0}^{s-1} \frac{m^* - j}{n - j}, and each factor is at most m∗/nm^*/n. Then q≤(m∗/n)sq \le (m^*/n)^s, part (c) does not apply as stated, and the success probability after k(m∗/n)k(m^*/n) rounds is 1−(1−q)k(m∗/n)1 - (1 - q)^{k(m^*/n)}, a little less than pp. For the example of the page, q=(52)/(82)=10/28≈0.357q = \binom{5}{2} / \binom{8}{2} = 10/28 \approx 0.357 against (5/8)2=0.390625(5/8)^2 = 0.390625. The gap shrinks as nn grows with m∗/nm^*/n fixed.

Remark (noise). Without noise, any sample of ss distinct points on one line gives that line, and the assumption of (c) holds. With noise, two close inliers can give a line far from the truth, so the assumption fails and the count of line L11 is optimistic. This is a statement about the model of the data, not a theorem about noisy data.

Complexity

The cost is given per round and for the number of rounds separately, as for any randomized sampler. One round costs the minimal solver, O(1)O(1) for a fixed model type such as a line, a homography or a fundamental matrix, plus nn residuals in line L7, so Θ(n)\Theta(n) in the real RAM. With kk rounds the time is Θ(kn)\Theta(k n), and the final refit adds O(n)O(n) for a fixed model type. The extra space is Θ(n)\Theta(n) for the two consensus sets.

The number of rounds kk is random. It is at most kmax⁡k_{\max}. Under the assumptions of the iteration bound, with a known inlier ratio ww, it is about log⁡(1−p)/log⁡(1−ws)\log(1 - p) / \log(1 - w^s), which grows like w−sln⁡11−pw^{-s} \ln \frac{1}{1 - p} for small wsw^s. This is exponential in ss: with w=0.5w = 0.5 and p=0.99p = 0.99, the count is 17 for s=2s = 2, 72 for s=4s = 4, 588 for s=7s = 7 and 1177 for s=8s = 8. So a solver with a smaller minimal sample, such as the five-point algorithm for the essential matrix instead of the eight-point algorithm, cuts the number of rounds sharply. This count is not a worst case; it is a bound under assumptions that noise breaks (see Pitfalls).

Properties

  • Randomized. Two runs with different seeds can return different answers. The guarantee holds with probability pp, not always.
  • Tolerates many outliers. RANSAC does not average over all items, so its answer does not depend on how far the outliers are. It can recover a model supported by fewer than half of the items, as long as no false model gets a larger consensus set.
  • Needs a threshold. The answer depends on ε\varepsilon, which must match the noise level. MSAC, MLESAC and MAGSAC change how the threshold enters the score.
  • Ties. The test in line L8 is strict, so among equal consensus sets the first one found wins.

Variants and improvements

  • Better scores. MSAC scores a model by a truncated quadratic cost and MLESAC by a likelihood, both from Torr and Zisserman (2000). MAGSAC removes the fixed threshold by marginalizing over the noise scale.
  • Local optimization. LO-RANSAC refits each new best model on its inliers inside the loop, which brings the count of rounds close to the formula.
  • Better sampling. PROSAC draws first from the matches of best quality. Guided sampling by Tordoff and Murray (2002) uses match scores as prior probabilities.
  • Faster verification. Preemptive RANSAC scores a fixed set of models on blocks of data under a time budget. Chum and Matas (2008) apply the sequential probability ratio test to stop the verification of a bad model early.
  • Several models. Sequential RANSAC removes the inliers of each found model and runs again. J-linkage clusters the data by the models they agree with. Efficient RANSAC finds planes, spheres and cylinders in point clouds.
  • A framework. USAC (Raguram et al., 2013) combines these parts into one pipeline.

When to use it

Use RANSAC when a model has a fast minimal solver, the residual of one item is cheap, and the outlier ratio is moderate, for example the homography, the fundamental matrix, the essential matrix and the camera pose from feature matches. Use it before a refinement that assumes inliers only, such as Levenberg-Marquardt on the reprojection error. If outliers are below about half of the data and the model is linear, least median of squares or an M-estimator is an option without a threshold. If the minimal sample is large and ww is small, the count w−sw^{-s} explodes; then use a smaller solver, a better ordering of the data (PROSAC) or a Hough transform for low-dimensional models.

Pitfalls

  • Trusting the count. The formula assumes that every all-inlier sample gives the correct model. With noise, an all-inlier sample of close points can give a poor model, so the real number of rounds is larger (Chum, Matas and Kittler, 2003). LO-RANSAC fixes much of this.
  • A wrong threshold. If ε\varepsilon is too small, true inliers fall out and the refit is noisy. If it is too large, outliers join, and a false model can win. Express ε\varepsilon in the units of the residual, for example pixels for the Sampson distance.
  • Degenerate samples. Two equal points give no line; three collinear points of four give no homography. The solver must detect these and return none, as in line L6. Some data are degenerate as a whole: a plane scene makes the fundamental matrix ill-defined, and RANSAC then returns a model with a large but wrong consensus set (Chum, Werner and Matas address this with DEGENSAC).
  • No final refit. The model of line L5 comes from ss noisy items only. Refit it on the consensus set, then recompute the consensus set if needed.
  • Unnormalized data. For homographies and fundamental matrices, fit with Hartley normalization, both in the minimal solver and in the refit.
  • A fixed seed in production. A fixed seed makes tests repeatable but can hide a rare failure. Test with several seeds.

Implementations

The Python code fits a line in the plane with s=2s = 2. The loop takes the minimal solver, the residual and the refit as arguments, so the same function fits other models. The refit is the total least squares line of the consensus set.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

ransac.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ransac/. The authors are listed in prov/648BZZ.jsonl.
"""RANSAC (random sample consensus), Fischler and Bolles 1981.

The loop is generic: it takes a minimal solver and a residual function. The
default model is a line in the plane, a x + b y + c = 0 with a^2 + b^2 = 1, fit
from s = 2 points, with the point-to-line distance as the residual. The number
of trials adapts to the best consensus set found so far:
k = ceil(log(1 - p) / log(1 - w^s)).
Standard library only. Cost: O(k (C + n)) for k trials, n data items and a
solver of cost C.
"""

import math
import random


def line_through(sample):
    """The line through two points, as (a, b, c) with a^2 + b^2 = 1, or None if they coincide."""
    (x1, y1), (x2, y2) = sample
    a, b = y1 - y2, x2 - x1
    nrm = math.hypot(a, b)
    if nrm == 0.0:
        return None
    a, b = a / nrm, b / nrm
    return canonical_line((a, b, -(a * x1 + b * y1)))


def canonical_line(line):
    """Fix the sign of (a, b, c): the first nonzero of a, b is positive."""
    a, b, c = line
    if a < 0 or (a == 0 and b < 0):
        return (-a, -b, -c)
    return (a, b, c)


def point_line_distance(line, pt):
    a, b, c = line
    return abs(a * pt[0] + b * pt[1] + c)


def fit_line_lsq(points, weights=None):
    """Total least squares line: minimizes the sum of (weighted) squared distances."""
    if weights is None:
        weights = [1.0] * len(points)
    sw = sum(weights)
    if len(points) < 2 or sw <= 0.0:
        return None
    mx = sum(w * p[0] for w, p in zip(weights, points)) / sw
    my = sum(w * p[1] for w, p in zip(weights, points)) / sw
    sxx = sum(w * (p[0] - mx) ** 2 for w, p in zip(weights, points))
    syy = sum(w * (p[1] - my) ** 2 for w, p in zip(weights, points))
    sxy = sum(w * (p[0] - mx) * (p[1] - my) for w, p in zip(weights, points))
    if sxx == 0.0 and syy == 0.0:
        return None
    theta = 0.5 * math.atan2(2.0 * sxy, sxx - syy)  # direction of the largest spread
    a, b = -math.sin(theta), math.cos(theta)
    return canonical_line((a, b, -(a * mx + b * my)))


def ransac_trials(p, w, s):
    """Smallest k with 1 - (1 - w^s)^k >= p, for 0 < p < 1 and 0 <= w <= 1."""
    q = w ** s
    if q >= 1.0:
        return 1
    if q <= 0.0:
        return math.inf
    return math.ceil(math.log(1.0 - p) / math.log1p(-q))


def ransac(data, threshold, rng=None, s=2, p=0.99, max_trials=10000,
           fit_minimal=line_through, residual=point_line_distance, refit=fit_line_lsq):
    """Return (model, inliers, trials).

    model is the refit of the best consensus set (or the sampled model if the
    refit fails), inliers is the sorted list of indices of the best consensus
    set, and trials is the number of samples drawn. Returns (None, [], trials)
    if no sample gives a model.
    """
    rng = rng if rng is not None else random.Random()
    n = len(data)
    if n < s:
        return None, [], 0
    best, best_inl, k, t = None, [], max_trials, 0  # @line L1
    while t < k:  # @line L2
        t += 1  # @line L3
        idx = rng.sample(range(n), s)  # @line L4
        theta = fit_minimal([data[i] for i in idx])  # @line L5
        if theta is None:  # @line L6
            continue
        inl = [i for i in range(n) if residual(theta, data[i]) <= threshold]  # @line L7
        if len(inl) > len(best_inl):  # @line L8
            best, best_inl = theta, inl  # @line L9
            w = len(best_inl) / n  # @line L10
            k = min(max_trials, ransac_trials(p, w, s))  # @line L11
    if best is None:  # @line L12
        return None, [], t
    model = refit([data[i] for i in best_inl]) if refit is not None else None  # @line L13
    return (model if model is not None else best), best_inl, t  # @line L14


def consensus_size(model, data, threshold, residual=point_line_distance):
    return sum(1 for x in data if residual(model, x) <= threshold)
test_ransac.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ransac/. The authors are listed in prov/648BZZ.jsonl.

import itertools
import math
import random

from ransac import (canonical_line, consensus_size, fit_line_lsq, line_through,
                    point_line_distance, ransac, ransac_trials)


def planted(rng, n_in, n_out, a=0.5, b=2.0, sigma=0.0, gap=1.0):
    """Inliers on y = a x + b (with optional noise), outliers at least gap away from the line."""
    pts = []
    for _ in range(n_in):
        x = rng.uniform(0.0, 10.0)
        pts.append((x, a * x + b + (rng.gauss(0.0, sigma) if sigma else 0.0)))
    true_line = line_through([(0.0, b), (1.0, a + b)])
    while len(pts) < n_in + n_out:
        q = (rng.uniform(0.0, 10.0), rng.uniform(-5.0, 12.0))
        if point_line_distance(true_line, q) > gap:
            pts.append(q)
    return pts, true_line


def line_angle(l1, l2):
    return math.atan2(abs(l1[0] * l2[1] - l1[1] * l2[0]), abs(l1[0] * l2[0] + l1[1] * l2[1]))


def test_trial_counts():
    assert [ransac_trials(0.99, 0.5, s) for s in (2, 3, 4, 5, 7, 8)] == [17, 35, 72, 146, 588, 1177]
    assert ransac_trials(0.99, 0.8, 4) == 9
    assert ransac_trials(0.95, 0.5, 2) == 11
    assert ransac_trials(0.99, 1.0, 4) == 1
    assert ransac_trials(0.99, 0.0, 4) == math.inf


def test_page_example():
    data = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (0, 4), (1, 3), (4, 0)]
    model, inl, _ = ransac(data, 0.1, random.Random(1))
    assert inl == [0, 1, 2, 3, 4]
    assert max(point_line_distance(model, data[i]) for i in inl) < 1e-12
    # the competing line x + y = 4 has 4 points
    assert consensus_size(line_through([(0, 4), (4, 0)]), data, 0.1) == 4


def test_planted_inliers_found_exactly():
    rng = random.Random(7)
    data, true_line = planted(rng, 60, 40)
    model, inl, _ = ransac(data, 0.05, random.Random(11))
    assert inl == list(range(60))
    assert line_angle(model, true_line) < 1e-9
    assert abs(model[2] - true_line[2]) < 1e-9


def test_matches_exhaustive_consensus():
    for seed in range(5):
        rng = random.Random(100 + seed)
        data, _ = planted(rng, 12, 10, gap=0.5)
        best = max(consensus_size(line_through(pq), data, 0.05)
                   for pq in itertools.combinations(data, 2) if line_through(pq) is not None)
        _, inl, _ = ransac(data, 0.05, random.Random(seed), p=0.999)
        assert len(inl) == best


def test_noisy_inliers():
    rng = random.Random(3)
    data, true_line = planted(rng, 50, 50, sigma=0.05, gap=0.5)
    model, inl, _ = ransac(data, 0.15, random.Random(5))
    assert set(range(50)) - set(inl) == set() or len(set(range(50)) - set(inl)) <= 1
    assert all(i < 50 for i in inl)
    assert line_angle(model, true_line) < math.radians(1.0)


def test_degenerate_data():
    model, inl, t = ransac([(1.0, 1.0)] * 5, 0.1, random.Random(0), max_trials=20)
    assert model is None and inl == [] and t == 20
    assert ransac([(0.0, 0.0)], 0.1, random.Random(0)) == (None, [], 0)


def test_fit_line_lsq():
    pts = [(x, 2.0 * x - 1.0) for x in range(6)]
    l = fit_line_lsq(pts)
    assert max(point_line_distance(l, q) for q in pts) < 1e-12
    assert canonical_line((-1.0, 0.0, 3.0)) == (1.0, 0.0, -3.0)

History

Fischler and Bolles of SRI International published RANSAC in Communications of the ACM in 1981. They used it for the location determination problem, the pose of a camera from image points of known landmarks, and they gave the expected number of trials w−sw^{-s} and its standard deviation. Robust regression in statistics had other answers at the same time: Rousseeuw proposed least median of squares in 1984, which also tries many random minimal fits but keeps the one of smallest median residual. In computer vision RANSAC became the default with the automatic estimation of two-view geometry in the 1990s, and the variants of the 2000s, from MLESAC to USAC, changed the score, the sampling and the verification step while keeping the loop.

References

  1. Martin A. Fischler and Robert C. Bolles, Random sample consensus: a paradigm for model fitting with applications to image analysis and automated cartography, Communications of the ACM 24(6), 1981, 381-395, The section on the RANSAC paradigm (the threshold, the number of trials with its mean and standard deviation, and the size of an acceptable consensus set)
  2. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 4.7, Robust estimation (RANSAC, the distance threshold, the number of samples and the adaptive rule), and Section 4.8, Automatic computation of a homography
  3. Ondrej Chum, Jiri Matas and Josef Kittler, Locally optimized RANSAC, Pattern Recognition, DAGM 2003, Lecture Notes in Computer Science 2781, 236-243, Section 1 (why the number of samples in practice is higher than the formula predicts: an all-inlier sample does not always give a model with all inliers)
  4. Rahul Raguram, Ondrej Chum, Marc Pollefeys, Jiri Matas and Jan-Michael Frahm, USAC: a universal framework for random sample consensus, IEEE Transactions on Pattern Analysis and Machine Intelligence 35(8), 2013, 2022-2038, Section 2 (the standard RANSAC loop, its stopping rule and its assumptions) and the survey of the variants in Sections 3 and 4
  5. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 8, Image alignment and stitching (robust least squares and RANSAC for feature-based alignment)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example