Algorithm Search⌘K

Algorithmadvanced

Preemptive RANSAC

Also called preemptive scoring RANSAC.

Generate a fixed set of hypotheses, score them on the data in random order, and keep only the better half after each block of data, so the time is fixed in advance.

Time
O(M (c + 2B) + M log M + N) worst · average · best
Space
Θ(M + N) extra
Where
B = the block size of the preemption function; M = the number of hypotheses; N = the number of observations; c = the cost of one minimal solve in units of one scoring
Properties
randomizednot exactofflineiterative
Origin
David Nistér, 2003

Preemptive RANSAC is a variant of RANSAC for real-time systems, where the time per frame is fixed and an answer must come in time. RANSAC works depth-first: it scores each hypothesis on all the data before it draws the next, and the number of hypotheses depends on the data. Preemptive RANSAC works breadth-first. It first generates a fixed number MM of hypotheses from random minimal samples. Then it puts the observations in random order and scores all hypotheses on the first observations; after every block of BB observations it drops the worse half of the hypotheses by their accumulated score, until one is left. So the total work is known in advance, at most Mτ+2BMM\tau + 2BM scorings, where τ\tau is the cost of one hypothesis. Nistér introduced it in 2003 for the live estimation of camera motion with the five-point algorithm.

In plain words

Imagine a contest with 500 runners and a fixed amount of time. You do not have time to let every runner run the full course. So you let all of them run a short stretch and send home the slower half. The others run another stretch, and again the slower half goes home. After a few rounds one runner is left.

Preemptive RANSAC does this with guesses. It makes all its guesses at the start. Then it checks all guesses against a few points of the data, in a random order, and throws away the worse half. The survivors are checked against a few more points, and so on. Good guesses get checked on many points; bad guesses are dropped after a few. The total work is the same every time, which is what a live video system needs.

The problem

The input is a set of NN observations, a minimal solver, a score ρ(o,h)\rho(o, h) of one observation oo for a hypothesis hh (here a cost, lower is better), the number of hypotheses MM and a preemption function f(i)f(i), the number of hypotheses that remain to be scored on observation ii. Nistér uses

f(i)=⌊M 2−⌊i/B⌋⌋,f(i) = \big\lfloor M \, 2^{-\lfloor i/B \rfloor} \big\rfloor,

which halves the number of hypotheses after each block of BB observations. The goal is the hypothesis with the best total score, found within a time that does not depend on the data. Preemptive RANSAC is a heuristic for this goal: it can drop the best hypothesis early.

The algorithm

The steps follow Algorithm 1 of Nistér (2003).

  1. PREEMPTIVE-RANSAC(D, M, B, ρ) ▷ N = |D|
  2. 1o_1, …, o_N ← the observations in random order
  3. 2h_1, …, h_M ← the models of M random minimal samples
  4. 3L(h) ← ρ(o_1, h) for every h; H ← all M hypotheses; i ← 2
  5. 4loop
  6. 5if i > N or f(i) ≤ 1 then return the h ∈ H of least L(h)
  7. 6if f(i) < |H| then H ← the f(i) hypotheses of H of least L
  8. 7L(h) ← L(h) + ρ(o_i, h) for every h ∈ H
  9. 8i ← i + 1

Line L6 needs only a partial order: the f(i)f(i) best hypotheses, in any order. A selection algorithm such as quickselect does it in O(∣H∣)O(|H|) time, as Nistér suggests; the code sorts, which costs O(∣H∣log⁡∣H∣)O(|H| \log |H|). The score is a design choice. The code uses the truncated quadratic ρ(o,h)=min⁡(r(o,h)2,T2)\rho(o, h) = \min(r(o, h)^2, T^2) of MSAC; any additive score with a ceiling works. Ties in line L6 are broken by the index of the hypothesis in the code.

Example

Take the 8 points of the RANSAC example, (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), with T=0.1T = 0.1. All hypotheses pass exactly through their inliers, so each observation costs 0 or T2=0.01T^2 = 0.01, and the accumulated cost is 0.010.01 times the number of outliers seen. Use M=8M = 8 hypotheses and B=2B = 2, so f(1),…,f(6)=8,4,4,2,2,1f(1), \ldots, f(6) = 8, 4, 4, 2, 2, 1. The hypotheses are

hh 0 1 2 3 4 5 6 7
line y=xy = x x+y=4x + y = 4 x=1x = 1 y=0y = 0 y=4y = 4 y=3y = 3 y=3xy = 3x 3x+y=43x + y = 4

With the seed 2, the order of the observations starts (0,4),(3,3),(4,4),(1,1),(2,2)(0,4), (3,3), (4,4), (1,1), (2,2). The table shows the number of outliers seen by each hypothesis still in play:

ii oio_i f(i)f(i) hypotheses kept, with outliers seen
1 (0,4)(0,4) 8 h0:1h_0{:}1, h1:0h_1{:}0, h2:1h_2{:}1, h3:1h_3{:}1, h4:0h_4{:}0, h5:1h_5{:}1, h6:1h_6{:}1, h7:0h_7{:}0
2 (3,3)(3,3) 4 h1:1h_1{:}1, h4:1h_4{:}1, h7:1h_7{:}1, h0:1h_0{:}1
3 (4,4)(4,4) 4 h0:1h_0{:}1, h1:2h_1{:}2, h4:1h_4{:}1, h7:2h_7{:}2
4 (1,1)(1,1) 2 h0:1h_0{:}1, h4:2h_4{:}2
5 (2,2)(2,2) 2 h0:1h_0{:}1, h4:3h_4{:}3

At i=6i = 6, f(6)=1f(6) = 1, and the run returns h0h_0, the line y=xy = x, after 8+4+4+2+2=208 + 4 + 4 + 2 + 2 = 20 scorings instead of the 6464 of full scoring. With the seed 3 the order starts (0,0),(0,4),(4,0),(2,2),(1,1)(0,0), (0,4), (4,0), (2,2), (1,1), three points of x+y=4x + y = 4 come first, and the run returns h1h_1, although h0h_0 has the lower total cost over all 8 points (0.030.03 against 0.040.04). Preemption trades this risk for a fixed time.

Correctness

The algorithm keeps an invariant at line L5: for every h∈Hh \in H, L(h)L(h) is the sum of ρ(oj,h)\rho(o_j, h) over j<ij < i, and HH holds the f(i−1)f(i-1) hypotheses that were best at each cut. The returned hypothesis has the least accumulated score among the survivors. The loop ends after at most NN steps, because ii grows by 1 and line L5 stops at i>Ni > N. The number of scorings is exactly M+∑i=2iendf(i)M + \sum_{i=2}^{i_{\text{end}}} f(i), which does not depend on the data. If f(i)=Mf(i) = M for all i≤Ni \le N, nothing is dropped and the result is the hypothesis of least total score, as in full scoring. With preemption, there is no guarantee that the best hypothesis survives; Nistér studies the chance of this under a simple inlier and outlier model. The proof is below.

Proof: Preemptive RANSAC returns the best survivor by accumulated score after a number of scorings fixed in advancefull

We use the notation of the page. There are N≥1N \ge 1 observations in the random order o1,…,oNo_1, \ldots, o_N of line L1, M≥1M \ge 1 hypotheses and the non-increasing preemption function f(i)=⌊M2−⌊i/B⌋⌋f(i) = \lfloor M 2^{-\lfloor i/B \rfloor} \rfloor with B≥1B \ge 1. The model of computation is the real RAM, and one scoring is one evaluation of ρ(o,h)\rho(o, h).

Claim. (a) At each test of line L5, every h∈Hh \in H has L(h)=∑j<iρ(oj,h)L(h) = \sum_{j < i} \rho(o_j, h), and ∣H∣=min⁡(M,f(i−1))|H| = \min(M, f(i-1)) for i≥3i \ge 3, ∣H∣=M|H| = M for i=2i = 2. (b) The loop ends, and the returned hypothesis has the least accumulated score in HH. (c) The number of scorings is M+∑i=2i∗min⁡(M,f(i))M + \sum_{i=2}^{i^*} \min(M, f(i)), where i∗i^* is the last i≤Ni \le N with f(i)≥2f(i) \ge 2 (and the sum is empty if there is none), so it does not depend on the data or on the random order. It is at most 2BM2BM. (d) If f(i)≥Mf(i) \ge M for all i≤Ni \le N, the result is a hypothesis of least total score ∑j=1Nρ(oj,h)\sum_{j=1}^N \rho(o_j, h) over all MM hypotheses.

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

Proof. At i=2i = 2, line L3 has set L(h)=ρ(o1,h)L(h) = \rho(o_1, h) for all MM hypotheses. Suppose the claim holds at the test of line L5 for some ii and the loop does not return. Line L6 keeps a subset of HH and does not change LL, and after it ∣H∣=min⁡(∣H∣,f(i))|H| = \min(|H|, f(i)). Since ff does not increase, and ∣H∣≤M|H| \le M, this is min⁡(M,f(i))\min(M, f(i)). Line L7 adds ρ(oi,h)\rho(o_i, h) to L(h)L(h) for every kept hh, so L(h)=∑j≤iρ(oj,h)L(h) = \sum_{j \le i} \rho(o_j, h). Line L8 raises ii by 1, and the claim holds at the next test. □\square

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

Proof. Each pass of the loop that does not return raises ii by 1, and line L5 returns once i>Ni > N. So the loop runs at most N−1N - 1 passes. Line L5 returns a hypothesis of least L(h)L(h) in HH, which by Lemma 1 is the least accumulated score among the survivors. HH is not empty: it starts with M≥1M \ge 1 hypotheses, and line L6 only runs when f(i)≥2f(i) \ge 2, so it keeps at least 2. □\square

Lemma 3 (count). Part (c) holds.

Proof. Line L3 makes MM scorings. A pass of the loop at index ii reaches line L7 exactly when i≤Ni \le N and f(i)≥2f(i) \ge 2, and then makes ∣H∣=min⁡(M,f(i))|H| = \min(M, f(i)) scorings by Lemma 1. Since ff does not increase, the passes that reach line L7 are those with 2≤i≤i∗2 \le i \le i^*. None of these quantities depends on the scores. For the bound, min⁡(M,f(i))≤M2−q\min(M, f(i)) \le M 2^{-q} with q=⌊i/B⌋q = \lfloor i/B \rfloor, and at most BB indices ii share a value of qq. If B≥2B \ge 2, the indices i≥2i \ge 2 with q=0q = 0 are 2,…,B−12, \ldots, B - 1, so the count is at most M+(B−2)M+∑q≥1BM2−q=(2B−1)M≤2BMM + (B - 2) M + \sum_{q \ge 1} B M 2^{-q} = (2B - 1) M \le 2BM. If B=1B = 1, then q=i≥2q = i \ge 2, and the count is at most M+∑q≥2M2−q=32M≤2BMM + \sum_{q \ge 2} M 2^{-q} = \frac{3}{2} M \le 2BM. □\square

Lemma 4 (no preemption). Part (d) holds.

Proof. If f(i)≥Mf(i) \ge M for all i≤Ni \le N, then line L6 never removes a hypothesis, since ∣H∣≤M≤f(i)|H| \le M \le f(i), and line L5 returns only at i=N+1i = N + 1 (note f(i)≥M≥2f(i) \ge M \ge 2 if M≥2M \ge 2; if M=1M = 1 the single hypothesis is the answer). By Lemma 1, L(h)L(h) is then the total score over all NN observations for every one of the MM hypotheses, and line L5 returns one of least total score. □\square

Remark (what is not proved). With preemption, a hypothesis of least total score can be dropped at a cut when its partial score on the first observations is worse than the partial scores of others. The example of the page with the seed 3 shows this. Nistér analyzes the probability of such losses under a simple model of inliers and outliers; the algorithm itself gives no guarantee that the best hypothesis survives.

Complexity

The cost is fixed in advance, as the design intends. The generation of the hypotheses costs MτM\tau in units of one scoring. The scoring costs ∑if(i)\sum_i f(i) scorings, and for f(i)=⌊M2−⌊i/B⌋⌋f(i) = \lfloor M 2^{-\lfloor i/B \rfloor} \rfloor this is at most BM(1+12+14+⋯ )≤2BMBM(1 + \frac12 + \frac14 + \cdots) \le 2BM. So the time is at most M(τ+2B)M(\tau + 2B) scorings, plus the selections of line L6, which cost O(M)O(M) in total with a linear-time selection, since ∣H∣|H| halves each time. For M=500M = 500, B=100B = 100 and N=500N = 500, the scorings are 99⋅500+100⋅250+100⋅125+100⋅62+100⋅31+15=9631599 \cdot 500 + 100 \cdot 250 + 100 \cdot 125 + 100 \cdot 62 + 100 \cdot 31 + 15 = 96315. The extra space is Θ(M+N)\Theta(M + N) for the hypotheses, their scores and the order of the observations. The front matter counts the code, which sorts instead of selecting.

Properties

  • Fixed time. The number of hypotheses and scorings is set by MM, BB and NN, not by the data.
  • Breadth-first. All hypotheses are scored on the same first observations, so their scores are comparable at each cut.
  • No adaptive stopping. Unlike RANSAC, the number of hypotheses does not adapt to the inlier ratio. If MM is too small for the outlier ratio, no hypothesis is correct and preemption cannot help.
  • Random observation order. The order of line L1 makes each block a random subset of the data, so the partial score is an unbiased estimate of the mean score per observation.

Variants and improvements

  • Other preemption functions. Any non-increasing ff works; Nistér discusses the trade-off between depth-first and breadth-first schemes and implements a hybrid.
  • Sequential tests. The test of Chum and Matas (2008), based on the sequential probability ratio test, stops the scoring of each hypothesis as soon as it is likely bad, depth-first, with a guarantee on the error of this decision.
  • Better hypotheses. PROSAC sampling can feed the hypothesis set, and LO-RANSAC can polish the winner.
  • Scores. The truncated quadratic of MSAC or a likelihood as in MLESAC both fit the additive scoring of line L7.

When to use it

Use preemptive RANSAC in real-time systems with a hard time budget, such as visual odometry from video, where a fair answer in time is better than the best answer late. Use it when the outlier ratio is known to be moderate, so that a fixed MM is enough. For offline estimation, where time can vary, plain RANSAC with adaptive stopping and LO-RANSAC are more reliable.

Pitfalls

  • MM too small. With inlier ratio ww and minimal sample size ss, the probability that no hypothesis is all-inlier is (1−ws)M(1 - w^s)^M. Choose MM by the iteration bound for the worst outlier ratio expected.
  • BB too small. With few observations per block, a good hypothesis can lose a cut by bad luck, as in the example with the seed 3.
  • Correlated observation order. If the observations are not shuffled, a block can come from one image region and favor a wrong model. Line L1 is required.
  • Unbounded scores. A score with no ceiling lets one gross outlier decide a cut. Use a bounded score.

Implementations

The Python code fits a line in the plane. The function preemptive_ransac takes an optional list of hypotheses, so the tests can fix them, and returns the number of scorings, which the tests compare with the formula. total_scorings gives the count M+∑i≥2f(i)M + \sum_{i \ge 2} f(i) without running the algorithm.

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.

preemptive_ransac.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/preemptive-ransac/. The authors are listed in prov/86C9V2.jsonl.
"""Preemptive RANSAC, Nister 2003 (Algorithm 1 of the paper).

A fixed number M of hypotheses is generated first. The observations are put in
random order and scored one at a time; after observation i only the f(i) best
hypotheses (by accumulated score) stay, with the preemption function
f(i) = floor(M * 2^(-floor(i / B))). The run ends when one hypothesis is left
or the observations are used up. The total work is fixed in advance, which
suits real-time systems.

The score of one observation is the truncated quadratic cost min(r^2, T^2)
(a choice of this code; lower is better). The model is a line in the plane,
a x + b y + c = 0 with a^2 + b^2 = 1, from 2 points. Standard library only.
"""

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
    if a < 0 or (a == 0 and b < 0):
        a, b = -a, -b
    return (a, b, -(a * x1 + b * y1))


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


def preemption(i, M, B):
    """f(i) = floor(M 2^(-floor(i/B)))."""
    return M >> (i // B)


def total_scorings(N, M, B):
    """M scorings for the first observation, then f(i) for i = 2, 3, ... until i > N or f(i) <= 1."""
    total = M
    for i in range(2, N + 1):
        f = preemption(i, M, B)
        if f <= 1:
            break
        total += min(f, M)
    return total


def make_hypotheses(data, M, rng, s=2, fit_minimal=line_through, max_tries=None):
    hyps = []
    if len(data) < s:
        return hyps
    tries = 0
    max_tries = max_tries if max_tries is not None else 10 * M
    while len(hyps) < M and tries < max_tries:
        tries += 1
        h = fit_minimal(rng.sample(data, s))
        if h is not None:
            hyps.append(h)
    return hyps


def preemptive_ransac(data, threshold, M=500, B=100, rng=None, s=2, hypotheses=None,
                      residual=point_line_distance):
    """Return (best_hypothesis, its accumulated cost, number of scorings)."""
    rng = rng if rng is not None else random.Random()
    t2 = threshold * threshold

    def rho(x, h):
        return min(residual(h, x) ** 2, t2)

    obs = list(data)
    rng.shuffle(obs)  # @line L1
    hyps = list(hypotheses) if hypotheses is not None else make_hypotheses(data, M, rng, s)  # @line L2
    if not hyps or not obs:
        return None, math.inf, 0
    M = len(hyps)
    scored = [(rho(obs[0], h), j) for j, h in enumerate(hyps)]  # @line L3
    count = len(scored)
    i = 2
    while True:  # @line L4
        f = preemption(i, M, B)
        if i > len(obs) or f <= 1:  # @line L5
            cost, j = min(scored)
            return hyps[j], cost, count
        if f < len(scored):  # @line L6
            scored = sorted(scored)[:f]
        scored = [(c + rho(obs[i - 1], hyps[j]), j) for c, j in scored]  # @line L7
        count += len(scored)
        i += 1  # @line L8
test_preemptive_ransac.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/preemptive-ransac/. The authors are listed in prov/86C9V2.jsonl.

import math
import random

from preemptive_ransac import (line_through, make_hypotheses, point_line_distance, preemption,
                               preemptive_ransac, total_scorings)

EXAMPLE = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (0, 4), (1, 3), (4, 0)]
PAIRS = [((0, 0), (3, 3)), ((0, 4), (4, 0)), ((1, 1), (1, 3)), ((0, 0), (4, 0)),
         ((0, 4), (4, 4)), ((1, 3), (3, 3)), ((0, 0), (1, 3)), ((1, 1), (0, 4))]
HYPS = [line_through(p) for p in PAIRS]


def full_cost(h, data, thr):
    return sum(min(point_line_distance(h, x) ** 2, thr * thr) for x in data)


def planted(rng, n_in, n_out, sigma=0.05):
    true_line = line_through([(0.0, 2.0), (1.0, 2.5)])
    pts = []
    for _ in range(n_in):
        x = rng.uniform(0.0, 10.0)
        pts.append((x, 0.5 * x + 2.0 + rng.gauss(0.0, sigma)))
    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) > 0.5:
            pts.append(q)
    return pts, true_line


def test_preemption_function():
    assert [preemption(i, 8, 2) for i in range(1, 9)] == [8, 4, 4, 2, 2, 1, 1, 0]
    assert total_scorings(8, 8, 2) == 20
    assert total_scorings(500, 500, 100) == 96315
    assert total_scorings(500, 500, 100) == sum(500 >> (i // 100) for i in range(1, 501))
    assert total_scorings(500, 500, 100) <= 2 * 100 * 500


def test_example_trace():
    h, cost, count = preemptive_ransac(EXAMPLE, 0.1, M=8, B=2, rng=random.Random(2), hypotheses=HYPS)
    assert h == HYPS[0] and abs(cost - 0.01) < 1e-12 and count == 20
    # another order of the observations keeps the wrong line
    h, cost, count = preemptive_ransac(EXAMPLE, 0.1, M=8, B=2, rng=random.Random(3), hypotheses=HYPS)
    assert h == HYPS[1] and count == 20
    assert full_cost(HYPS[0], EXAMPLE, 0.1) < full_cost(HYPS[1], EXAMPLE, 0.1)


def test_no_preemption_is_full_scoring():
    for seed in range(3):
        data, _ = planted(random.Random(seed), 30, 30)
        hyps = make_hypotheses(data, 40, random.Random(seed))
        h, cost, count = preemptive_ransac(data, 0.15, M=40, B=1000, rng=random.Random(seed), hypotheses=hyps)
        costs = [full_cost(g, data, 0.15) for g in hyps]
        assert count == 40 * 60
        assert abs(cost - min(costs)) < 1e-9
        assert abs(full_cost(h, data, 0.15) - min(costs)) < 1e-9


def test_scorings_match_formula():
    data, _ = planted(random.Random(5), 250, 250)
    _, _, count = preemptive_ransac(data, 0.15, M=500, B=100, rng=random.Random(1))
    assert count == total_scorings(500, 500, 100) == 96315


def test_planted_line():
    for seed in range(3):
        data, true_line = planted(random.Random(10 + seed), 100, 100)
        h, _, _ = preemptive_ransac(data, 0.15, M=100, B=20, rng=random.Random(seed))
        ang = math.atan2(abs(h[0] * true_line[1] - h[1] * true_line[0]),
                         abs(h[0] * true_line[0] + h[1] * true_line[1]))
        assert ang < math.radians(3.0) and abs(h[2] - true_line[2]) < 0.3


def test_empty():
    assert preemptive_ransac([], 0.1, M=4, B=2, rng=random.Random(0)) == (None, math.inf, 0)

History

Nistér presented preemptive RANSAC at ICCV 2003, with a journal version in Machine Vision and Applications in 2005. It was the robust core of a system that estimated the motion of a calibrated camera from video in real time, with the five-point solver for the essential matrix and three-point pose for later frames. Later work on fast verification, such as the sequential test of Chum and Matas (2008) and the USAC framework of 2013, chose depth-first verification with early rejection instead.

References

  1. David Nistér, Preemptive RANSAC for live structure and motion estimation, ICCV 2003, Algorithm 1 (preemptive scoring), the preemption function f(i) = floor(M 2^(-floor(i/B))), the time t(f) and Table 1 (M = 500, B = 100)
  2. David Nistér, Preemptive RANSAC for live structure and motion estimation, Machine Vision and Applications 16(5), 2005, 321-329, The journal version of the same method
  3. 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, The survey of methods that speed up the verification of hypotheses, including preemptive RANSAC

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