Algorithmadvanced
PROSAC
Also called progressive sample consensus.
RANSAC that draws samples first from the matches of best quality and grows the pool over time, which finds a good model much sooner when the ranking is good.
- Solves
- Robust model fitting
- Time
- Θ(k n + 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
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ondrej Chum, Jiri Matas, 2005
PROSAC (progressive sample consensus) is a variant of RANSAC that changes only which samples are drawn. In image matching, each tentative match comes with a quality score, for example the distance ratio of the Lowe ratio test, and matches with good scores are more often correct. RANSAC ignores the scores and samples uniformly. PROSAC sorts the matches by score and draws its first samples from a small set of the best matches, then lets the set grow, so that after many samples it draws from all matches as RANSAC does. When the ranking is good, a sample of inliers comes up after very few draws, often orders of magnitude fewer than RANSAC needs. When the ranking is random, PROSAC behaves like RANSAC in experiments. Chum and Matas introduced it in 2005, with a stopping rule that also picks the size of the set of matches.
In plain words
You must find a line among many dots, and someone has ranked the dots: the dots at the top of the list are probably good, the dots at the bottom are probably junk. The ranking is not perfect, but it helps.
RANSAC picks dots at random from the whole list. PROSAC starts at the top. Its first guesses use only the first few dots. Then, step by step, it lets one more dot from further down into the pool, and each new guess uses the newest dot together with dots from the pool. Over time the pool becomes the whole list.
If the top of the list is mostly good dots, an early guess is right, and PROSAC can stop. The stopping test also says how far down the list the good dots go.
The problem
The input is as for RANSAC, with the data sorted by a quality score, best first, and a minimal sample size . Write for the best items. PROSAC has four more parameters: , the number of samples after which it draws from all of ; , the probability that an item is an inlier of a wrong model by chance; and and , the error probabilities of the two parts of the stopping rule. The goal is a model with a large consensus set, found with few samples.
The algorithm
The growth function decides when the pool grows. Let , the expected number of samples, among uniform samples from , that lie in . Then . Let and , and . By eq. (6) of the paper, the -th sample is together with items drawn at random from . Each new item thus enters with the share of samples that RANSAC would give to samples whose worst item is that one.
PROSAC(u_1, …, u_N, m, ε, k_max) ▷ sorted by quality, best first- 1
t ← 0, n ← m, n* ← N, k* ← k_max, θ* ← none, I* ← ∅ - 2
while t < k* do - 3
t ← t + 1 - 4
while t > T'_n and n < n* do ▷ n becomes g(t) - 5
n ← n + 1 - 6
if t ≤ T'_n then - 7
S ← {u_n} ∪ (m − 1 items of U_{n−1}, drawn at random) - 8
else S ← m items of U_n, drawn at random ▷ the pool stopped at n* - 9
θ ← FIT-MINIMAL(S); if θ is none then continue - 10
I ← {x ∈ D : r(θ, x) ≤ ε} - 11
if |I| > |I*| then - 12
θ* ← θ, I* ← I - 13
(n*, k*) ← the prefix that passes the non-randomness test with the least k_n, with n* ≥ n - 14
return θ*, I*
The stopping rule of line L13 looks at the inliers of the best model in each prefix. Let . Non-randomness: a wrong model also gets inliers by chance, and the number of such inliers in , besides the items of its sample, is binomial with parameters and . The test asks , the least such that the probability of or more chance inliers is below . Maximality: with , the probability that a sample from is all-inlier, the number of samples after which a better model in would have been missed with probability below is . Among the prefixes that pass the first test, minimizes , and PROSAC stops after samples. The paper uses and .
Read literally, the two branches of step 2 of Algorithm 1 in the paper are swapped with respect to eq. (6). The code and the pseudocode follow eq. (6): while the pool grows, each sample contains the newest item . The paper prints the probability of chance inliers in as ; the exponent appears to be a typo, and the code uses the binomial form , whose terms sum to 1.
Example
Take points sorted by quality: . Six of them lie on ; in the sorted order the inliers are at positions 1, 3, 4, 6, 7 and 9. Use , , and . Then and : the pool is complete after samples. With the seed 0 the code draws:
| sample | line | |||||
|---|---|---|---|---|---|---|
| 1 | 2 | 2 | 10 | |||
| 2 | 3 | 3 | 10 | |||
| 3 | 3 | 6 | 7 | 5 | ||
| 4 | 4 | through | 2 | 7 | 5 | |
| 5 | 4 | 6 | 7 | 5 |
After round 2, no prefix passes the non-randomness test, so stays at the cap. After round 3, the inlier counts of the prefixes are , and the thresholds are . The prefixes pass. For , and ; for , and ; the other prefixes need 6 or more. So and , and PROSAC stops after 5 samples. The correct line came from the third sample. RANSAC with and would ask for 11 samples.
Correctness
PROSAC keeps the invariant of RANSAC: is the largest consensus set among the sampled models. Each sample consists of distinct items of the current pool, and the loop ends after at most rounds. The growth function has an exact meaning: by round , PROSAC has drawn samples whose worst item is , the expected number of such samples in uniform samples rounded up. When the pool stops at after the schedule, PROSAC samples exactly as RANSAC does. The stopping rule is a test with error probabilities and under its assumptions, not a bound. Chum and Matas state that they could not prove that PROSAC is never worse than RANSAC in the worst case; with a random ordering, the two performed the same in their experiments (a benchmark result). The proof of the invariants is below.
Proof: PROSAC draws valid samples on the schedule of its growth function, keeps the largest consensus set and stopsfull
We use the notation of the page: sorted by quality, , the sample size, , , and . The minimal solver and the residual are correct subroutines, and the model of computation is the real RAM.
Claim. (a) , and is the expected number of samples in among independent uniform samples of distinct items of . (b) In every round, the sample consists of distinct items of for the current . In a round with , the current equals , and is together with distinct items of . (c) At each test of line L2, is the largest consensus set among the sampled models. (d) The loop ends after at most rounds. (e) For and , the samples are uniform among the -subsets of , as in RANSAC.
Lemma 1. Part (a) holds.
Proof. , which gives the recurrence. A uniform sample of distinct items lies in with probability , so by linearity of expectation samples contain such samples on average.
Lemma 2. Part (b) holds.
Proof. The sequence does not decrease, since each step adds (by Lemma 1, ). Lines L4 and L5 raise only when , and never decreases. We show that at line L6 whenever . If was raised to its current value in this round, the raise happened because . Otherwise it was raised in an earlier round with . Now let . Every has , because does not decrease, so is the least index with , that is, ; for this holds because is the least index. Line L7 then takes and distinct items of (the set has items since ), so has distinct items of . Otherwise and line L8 draws distinct items of , with .
Lemma 3. Part (c) holds.
Proof. As for RANSAC: before the first round ; line L11 replaces exactly when the consensus set of the new model is larger, so stays the largest among the sampled models.
Lemma 4. Part (d) holds.
Proof. starts at , and line L13 sets it to only when , or back to when no prefix passes the test. So at all times, and since grows by 1 per round, the test of line L2 fails after at most rounds.
Lemma 5. Part (e) holds.
Proof. With , lines L4 and L5 raise up to , and after round the test of line L6 fails, so line L8 draws distinct items of uniformly.
Remark (the schedule). By Lemma 2, the rounds with are , so while the pool grows, exactly samples have as their worst item. By Lemma 1, is the expected number of samples with worst item among uniform samples. So PROSAC draws the samples of a RANSAC run of length in the order of their worst item, with each count rounded up. If , then is an integer and .
Remark (what is not proved). The stopping rule controls two error probabilities, for a model supported by chance and for a better model missed in , under the binomial model of chance inliers. It is not a guarantee of the largest consensus set. Chum and Matas state that they could not prove that PROSAC is never slower than RANSAC; the equal behavior on random orderings is a benchmark result.
Complexity
One round costs the minimal solver plus residuals, so in the real RAM, as in RANSAC. The schedule costs . The table of thresholds costs if each tail sum is computed directly; it depends only on , , and and can be computed once. Each new best model costs for the prefix counts in line L13. With rounds, the time is with the table, and when the table is given. The extra space is . Sorting by quality adds when the data are not sorted. The number of rounds is random and at most . With a good ranking it is usually far below the RANSAC count for the whole data (a benchmark result of Chum and Matas).
Properties
- Uses only the order of the scores. PROSAC needs no calibrated probability for each match, only a ranking.
- Draws the samples of RANSAC in a different order. The growth function hands out samples to each prefix in proportion to what uniform samples would give it.
- Repeats samples early. For small , the pool has few distinct samples, so some are drawn more than once. With and , the first 82 samples all come from the 3 best items; choose with the size of the data in mind.
- Finds the extent of the inliers. is an estimate of how far down the ranking the inliers reach.
Variants and improvements
- Guided sampling of Tordoff and Murray (2002) turns the match scores into prior inlier probabilities and samples by them; it needs calibrated scores, PROSAC does not.
- USAC (Raguram et al., 2013) uses PROSAC as its sampling stage, together with LO-RANSAC and early rejection of bad models.
- Any score works. The sampling of PROSAC can be combined with the costs of MSAC, MLESAC or MAGSAC, since it changes only which samples are drawn.
- Spatial priors. NAPSAC (Myatt et al., 2002) draws the items of a sample from a neighborhood, and progressive NAPSAC (Barath et al., 2020) grows these neighborhoods in the manner of PROSAC.
When to use it
Use PROSAC when each datum has a score that correlates with being an inlier, as in feature matching with descriptor distances, and the outlier ratio is high. Without a meaningful score, it brings nothing over RANSAC and adds the cost of the stopping test. If the score is calibrated as a probability, guided sampling can also be used.
Pitfalls
- A misleading ranking. If the best-scored matches are systematically wrong, for example repeated texture that gives confident false matches, the early samples are wasted. The growth function limits the damage, because the pool grows anyway.
- Too large for small data. The growth is slow, and early samples repeat (see Properties).
- The swapped branches. An implementation that copies step 2 of Algorithm 1 literally, instead of eq. (6), draws the samples in a different order than the paper describes.
- A wrong . If is too small, the non-randomness test passes too easily and PROSAC can stop on a wrong model. Estimate from the threshold and the size of the region where outliers fall.
Implementations
The Python code fits a line in the plane with . The functions growth_schedule, min_inliers_table and choose_n_star give the schedule , the thresholds and the choice of separately, so the tests check each one, and a test checks that each sample contains .
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/prosac/. The authors are listed in prov/B0M487.jsonl.
"""PROSAC (progressive sample consensus), Chum and Matas 2005.
The data come sorted by a quality score, best first. PROSAC draws its samples
from a growing prefix U_n of the sorted data: by the growth function, the t-th
sample is u_n (the n-th item) together with m - 1 items drawn from U_{n-1},
where n = g(t) = min{n : T'_n >= t}, as in eq. (6) of the paper. Once the
prefix stops growing at n*, samples are drawn from U_{n*} uniformly, as in
RANSAC. The stopping rule picks n* to minimize the number of samples needed
for the prefix, among prefixes whose inlier count passes a non-randomness test.
The model is a line in the plane, a x + b y + c = 0 with a^2 + b^2 = 1, from
m = 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 growth_schedule(N, m, T_N):
"""Return {n: T'_n} for n = m..N, with T'_m = 1 and T'_{n+1} = T'_n + ceil(T_{n+1} - T_n)."""
T = float(T_N)
for i in range(m):
T *= (m - i) / (N - i) # T_m = T_N C(m, m) / C(N, m)
Tp = {m: 1}
for n in range(m, N):
T_next = T * (n + 1) / (n + 1 - m)
Tp[n + 1] = Tp[n] + math.ceil(T_next - T)
T = T_next
return Tp
def min_inliers_table(N, m, beta, psi):
"""I_n^min = min{j : sum_{i=j}^n P^R_n(i) < psi}, P^R_n(i) binomial(n - m, beta) at i - m."""
table = {}
for n in range(m, N + 1):
tail = 0.0
j = n + 1
for i in range(n, m - 1, -1):
tail += math.comb(n - m, i - m) * beta ** (i - m) * (1.0 - beta) ** (n - i)
if tail >= psi:
break
j = i
table[n] = j
return table
def samples_needed(I_n, n, m, eta0):
"""k_n(eta0) = log(eta0) / log(1 - P_In), P_In = prod_{j<m} (I_n - j) / (n - j)."""
if I_n < m:
return math.inf
P = 1.0
for j in range(m):
P *= (I_n - j) / (n - j)
if P >= 1.0:
return 1
return math.ceil(math.log(eta0) / math.log1p(-P))
def choose_n_star(is_inlier, m, imin, eta0, max_trials):
"""Over prefixes n that pass the non-randomness test, minimize k_n. Returns (n*, k*)."""
best_n, best_k = len(is_inlier), max_trials
count = sum(is_inlier[:m - 1])
for n in range(m, len(is_inlier) + 1):
count += is_inlier[n - 1]
if count >= imin[n]:
k_n = samples_needed(count, n, m, eta0)
if k_n < best_k:
best_n, best_k = n, k_n
return best_n, best_k
def prosac(data, eps, rng=None, m=2, T_N=200000, beta=0.05, psi=0.05, eta0=0.05,
max_trials=10000, fit_minimal=line_through, residual=point_line_distance):
"""data sorted by quality, best first. Return (model, inliers, trials, n_star)."""
rng = rng if rng is not None else random.Random()
N = len(data)
if N < m:
return None, [], 0, N
Tp = growth_schedule(N, m, T_N)
imin = min_inliers_table(N, m, beta, psi)
t, n, n_star, k_star = 0, m, N, max_trials # @line L1
best, best_inl = None, []
while t < k_star: # @line L2
t += 1 # @line L3
while t > Tp[n] and n < n_star: # @line L4
n += 1 # @line L5
if t <= Tp[n]: # @line L6
idx = [n - 1] + rng.sample(range(n - 1), m - 1) # @line L7
else:
idx = rng.sample(range(n), m) # @line L8
theta = fit_minimal([data[i] for i in idx]) # @line L9
if theta is None:
continue
flags = [1 if residual(theta, x) <= eps else 0 for x in data] # @line L10
if sum(flags) > len(best_inl): # @line L11
best, best_inl = theta, [i for i in range(N) if flags[i]] # @line L12
n_star, k_star = choose_n_star(flags, m, imin, eta0, max_trials) # @line L13
n_star = max(n_star, n)
return best, best_inl, t, n_star # @line L14
test_prosac.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/prosac/. The authors are listed in prov/B0M487.jsonl.
import math
import random
from prosac import (choose_n_star, growth_schedule, line_through, min_inliers_table, point_line_distance,
prosac, samples_needed)
EXAMPLE = [(0, 0), (0, 3), (2, 2), (5, 5), (4, 1), (1, 1), (3, 3), (2, 5), (4, 4), (5, 2)]
def planted(rng, n_in, n_out, good_order=True):
true_line = line_through([(0.0, 2.0), (1.0, 2.5)])
items = []
for _ in range(n_in):
x = rng.uniform(0.0, 10.0)
items.append((rng.uniform(0.0, 0.3) if good_order else rng.random(), (x, 0.5 * x + 2.0), True))
while len(items) < n_in + n_out:
q = (rng.uniform(0.0, 10.0), rng.uniform(-5.0, 12.0))
if point_line_distance(true_line, q) > 1.0:
items.append((rng.uniform(0.1, 1.0) if good_order else rng.random(), q, False))
items.sort(key=lambda z: z[0])
return [p for _, p, _ in items], [i for i, z in enumerate(items) if z[2]]
def test_schedule_counts_subsets():
for m in (2, 3):
Tp = growth_schedule(12, m, math.comb(12, m))
assert all(Tp[n] == math.comb(n, m) for n in range(m, 13))
Tp = growth_schedule(100, 2, 200000)
assert Tp[2] == 1 and Tp[3] == 82
assert all(Tp[n + 1] >= Tp[n] for n in range(2, 100))
def test_samples_follow_eq6():
data = [(float(i), float(i * i % 7)) for i in range(15)]
where = {p: i for i, p in enumerate(data)}
seen = []
def solver(sample):
seen.append(sorted(where[p] for p in sample))
return line_through(sample)
Tp = growth_schedule(15, 2, 105)
prosac(data, 1e-9, random.Random(4), T_N=105, max_trials=60, fit_minimal=solver)
for t, idx in enumerate(seen, start=1):
g = min(n for n in Tp if Tp[n] >= t)
assert idx[-1] == g - 1 and idx[0] < g - 1
def test_min_inliers_table():
imin = min_inliers_table(30, 2, 0.05, 0.05)
for n in range(2, 31):
def tail(j):
return sum(math.comb(n - 2, i - 2) * 0.05 ** (i - 2) * 0.95 ** (n - i) for i in range(j, n + 1))
j = imin[n]
assert tail(j) < 0.05 and (j == 2 or tail(j - 1) >= 0.05)
def test_example_stopping():
flags = [1, 0, 1, 1, 0, 1, 1, 0, 1, 0]
imin = min_inliers_table(10, 2, 0.05, 0.05)
assert [imin[n] for n in range(2, 11)] == [3, 4, 4, 4, 4, 4, 4, 4, 5]
assert choose_n_star(flags, 2, imin, 0.05, 10000) == (7, 5)
assert samples_needed(5, 7, 2, 0.05) == 5 and samples_needed(4, 6, 2, 0.05) == 6
def test_example_run():
model, inl, t, n_star = prosac(EXAMPLE, 0.1, random.Random(0), T_N=45)
assert inl == [0, 2, 3, 5, 6, 8] and t == 5 and n_star == 7
assert abs(model[0] - math.sqrt(0.5)) < 1e-12 and abs(model[0] + model[1]) < 1e-12
def test_good_ordering_is_fast():
for seed in range(3):
data, true_in = planted(random.Random(seed), 30, 70)
_, inl, t, _ = prosac(data, 0.05, random.Random(seed), T_N=math.comb(100, 2))
assert inl == true_in
assert t < 49 # RANSAC needs 49 samples for p = 0.99 at w = 0.3
def test_random_ordering_still_works():
for seed in range(3):
data, true_in = planted(random.Random(10 + seed), 30, 70, good_order=False)
_, inl, _, _ = prosac(data, 0.05, random.Random(seed), T_N=math.comb(100, 2))
assert inl == true_in
def test_small_input():
assert prosac([(0.0, 0.0)], 0.1, random.Random(0)) == (None, [], 0, 1)
History
Chum and Matas presented PROSAC at CVPR 2005. Tordoff and Murray had used match scores in guided MLESAC in 2002, but they needed the scores as probabilities. PROSAC needed only the order, and it gave a stopping rule that finds the size of the reliable part of the ranking. It became the sampling stage of USAC (2013).
References
- Ondrej Chum and Jiri Matas, Matching with PROSAC: progressive sample consensus, IEEE Conference on Computer Vision and Pattern Recognition 2005, volume 1, 220-226, Section 2 (the growth function, T_n and T'_n, and the samples of eq. (6)), Section 2.2 (the stopping rule: non-randomness and maximality) and Algorithm 1
- Ben J. Tordoff and David W. Murray, Guided sampling and consensus for motion estimation, European Conference on Computer Vision 2002, Lecture Notes in Computer Science 2350, 82-96, Guided sampling with match scores as prior inlier probabilities, the earlier method that PROSAC compares with
- 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, PROSAC as the sampling stage of the framework
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 B0M487 Edit this page History Report an error Markdown