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.
- Solves
- Robust model fitting
- 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
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 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 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 scorings, where 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 observations, a minimal solver, a score of one observation for a hypothesis (here a cost, lower is better), the number of hypotheses and a preemption function , the number of hypotheses that remain to be scored on observation . Nistér uses
which halves the number of hypotheses after each block of 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).
PREEMPTIVE-RANSAC(D, M, B, ρ) ▷ N = |D|- 1
o_1, …, o_N ← the observations in random order - 2
h_1, …, h_M ← the models of M random minimal samples - 3
L(h) ← ρ(o_1, h) for every h; H ← all M hypotheses; i ← 2 - 4
loop - 5
if i > N or f(i) ≤ 1 then return the h ∈ H of least L(h) - 6
if f(i) < |H| then H ← the f(i) hypotheses of H of least L - 7
L(h) ← L(h) + ρ(o_i, h) for every h ∈ H - 8
i ← i + 1
Line L6 needs only a partial order: the best hypotheses, in any order. A selection algorithm such as quickselect does it in time, as Nistér suggests; the code sorts, which costs . The score is a design choice. The code uses the truncated quadratic 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, , with . All hypotheses pass exactly through their inliers, so each observation costs 0 or , and the accumulated cost is times the number of outliers seen. Use hypotheses and , so . The hypotheses are
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|---|
| line |
With the seed 2, the order of the observations starts . The table shows the number of outliers seen by each hypothesis still in play:
| hypotheses kept, with outliers seen | |||
|---|---|---|---|
| 1 | 8 | , , , , , , , | |
| 2 | 4 | , , , | |
| 3 | 4 | , , , | |
| 4 | 2 | , | |
| 5 | 2 | , |
At , , and the run returns , the line , after scorings instead of the of full scoring. With the seed 3 the order starts , three points of come first, and the run returns , although has the lower total cost over all 8 points ( against ). Preemption trades this risk for a fixed time.
Correctness
The algorithm keeps an invariant at line L5: for every , is the sum of over , and holds the hypotheses that were best at each cut. The returned hypothesis has the least accumulated score among the survivors. The loop ends after at most steps, because grows by 1 and line L5 stops at . The number of scorings is exactly , which does not depend on the data. If for all , 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 observations in the random order of line L1, hypotheses and the non-increasing preemption function with . The model of computation is the real RAM, and one scoring is one evaluation of .
Claim. (a) At each test of line L5, every has , and for , for . (b) The loop ends, and the returned hypothesis has the least accumulated score in . (c) The number of scorings is , where is the last with (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 . (d) If for all , the result is a hypothesis of least total score over all hypotheses.
Lemma 1 (invariant). Part (a) holds.
Proof. At , line L3 has set for all hypotheses. Suppose the claim holds at the test of line L5 for some and the loop does not return. Line L6 keeps a subset of and does not change , and after it . Since does not increase, and , this is . Line L7 adds to for every kept , so . Line L8 raises by 1, and the claim holds at the next test.
Lemma 2 (termination and result). Part (b) holds.
Proof. Each pass of the loop that does not return raises by 1, and line L5 returns once . So the loop runs at most passes. Line L5 returns a hypothesis of least in , which by Lemma 1 is the least accumulated score among the survivors. is not empty: it starts with hypotheses, and line L6 only runs when , so it keeps at least 2.
Lemma 3 (count). Part (c) holds.
Proof. Line L3 makes scorings. A pass of the loop at index reaches line L7 exactly when and , and then makes scorings by Lemma 1. Since does not increase, the passes that reach line L7 are those with . None of these quantities depends on the scores. For the bound, with , and at most indices share a value of . If , the indices with are , so the count is at most . If , then , and the count is at most .
Lemma 4 (no preemption). Part (d) holds.
Proof. If for all , then line L6 never removes a hypothesis, since , and line L5 returns only at (note if ; if the single hypothesis is the answer). By Lemma 1, is then the total score over all observations for every one of the hypotheses, and line L5 returns one of least total score.
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 in units of one scoring. The scoring costs scorings, and for this is at most . So the time is at most scorings, plus the selections of line L6, which cost in total with a linear-time selection, since halves each time. For , and , the scorings are . The extra space is 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 , and , 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 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 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 is enough. For offline estimation, where time can vary, plain RANSAC with adaptive stopping and LO-RANSAC are more reliable.
Pitfalls
- too small. With inlier ratio and minimal sample size , the probability that no hypothesis is all-inlier is . Choose by the iteration bound for the worst outlier ratio expected.
- 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 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.
# 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 86C9V2 Edit this page History Report an error Markdown