Algorithmadvanced
LO-RANSAC
Also called locally optimized RANSAC.
RANSAC that, each time a sample gives a new best model, refines it by least squares fits on its inliers, so the number of samples comes close to the count the formula predicts.
- Solves
- Robust model fitting
- 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
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ondrej Chum, Jiri Matas, Josef Kittler, 2003
LO-RANSAC (locally optimized RANSAC) is a variant of RANSAC that adds a refinement step inside the loop. Each time a model from a minimal sample has more inliers than any earlier one, LO-RANSAC fits new models to the inliers of that model by least squares and keeps the best of them. The reason is noise: a model from a minimal sample of inliers is often tilted by the noise of its few items, so it misses many inliers and RANSAC must keep sampling until a lucky sample gives a better one. A least squares fit to many inliers averages the noise away. The step runs rarely, about times in samples, so it adds little to the total time, and the number of samples comes close to the count of the iteration bound. Chum, Matas and Kittler introduced it in 2003, and Lebeda, Matas and Chum gave the current form of the step in 2012.
In plain words
RANSAC guesses a line from two dots and counts the dots close to it. Even if both dots are good, they have small errors, and the line through them can tilt. A tilted line passes far from the good dots at the ends, so the count is too low. RANSAC then needs many more guesses before two dots happen to give a straight enough line.
LO-RANSAC fixes this. When a guess beats all earlier guesses, it does not stop there. It takes the dots that agree with the guess and fits a line through all of them at once, which averages out the small errors. It does this a few times, with a slightly wider band of agreement at first and a narrower one later. The improved line usually agrees with more dots, so the search can stop earlier.
The problem
The input is as for RANSAC: data , a minimal solver for samples of items, a residual , a threshold , a confidence and a cap . LO-RANSAC also needs a least squares solver that fits a model to any number of items, and four parameters of the local step: a factor for a wider threshold, a number of repetitions, a number of inner iterations and a size of the non-minimal samples. The goal is a model with a large consensus set .
The algorithm
LO-RANSAC(D, s, ε, p, k_max) ▷ n = |D|- 1
θ* ← none, I* ← ∅, n_s ← 0, k ← k_max, t ← 0 - 2
while t < k do - 3
t ← t + 1 - 4
S ← s distinct items of D, drawn uniformly at random - 5
θ ← FIT-MINIMAL(S) ▷ none for a degenerate sample - 6
if θ is none then continue - 7
I ← I(θ) - 8
if |I| > n_s then ▷ best minimal-sample model so far - 9
n_s ← |I| - 10
(θ_L, I_L) ← LOCAL-OPT(θ, I) - 11
if |I_L| > |I*| then - 12
θ* ← θ_L, I* ← I_L - 13
k ← min(k_max, ⌈log(1 − p) / log(1 − (|I*|/n)^s)⌉) - 14
if θ* is none then return failure - 15
return θ*, I* LOCAL-OPT(θ, I) ▷ keeps the model with most inliers at ε- 16
best ← (θ, I) - 17
try FIT-LSQ({x : r(θ, x) ≤ m_θ ε}) - 18
repeat reps times - 19
S ← min(s_is, ⌊|I|/2⌋) items of I, drawn at random (at least s) - 20
θ' ← FIT-LSQ(S) - 21
θ' ← FIT-LSQ(I(θ')), ε' ← m_θ ε - 22
repeat iters times - 23
try θ' - 24
θ' ← FIT-LSQ({x : r(θ', x) ≤ ε'}) - 25
ε' ← ε' − (m_θ ε − ε)/(iters − 1) - 26
return best, after a last try of θ'
Here "try " means: compute and replace best if it has more inliers. Lines L8 and L9 follow Algorithm 1 of Lebeda, Matas and Chum: the local step runs when a minimal-sample model beats every earlier minimal-sample model, not every model found by the local step. Lines L18 to L25 follow their Algorithms 2 and 3: an inner RANSAC on non-minimal samples drawn from the inliers, each followed by iterated least squares while the threshold shrinks from to . Their Table 1 gives , 10 repetitions, 4 iterations and for homographies and 14 for epipolar geometry; the code uses the same values except for a line. Their Algorithm 3 also weights the items; the code uses unit weights.
Example
Take 14 points: the 10 inliers for with , which lie near , and the 4 outliers . Use , and , so the wide threshold is about 0.113.
The sample gives the line , which tilts across the band. Its inliers at are the 5 points with , so plain RANSAC would set .
LO-RANSAC runs the local step. Line L17 takes the 7 points within 0.113 of the line, , and fits them by least squares. The new line is about , and all 10 inliers are within 0.08 of it. The best model now has 10 inliers, and line L13 sets .
Plain RANSAC would need a sample whose line has all 10 inliers. Only 4 of the 91 pairs of points give such a line, the pairs , so its count of samples stays high much longer. With the seed 1, the code stops after 7 samples with all 10 inliers and 2 runs of the local step.
Correctness
The loop of LO-RANSAC keeps an invariant at line L2: has the most inliers among all models evaluated so far, both the models of the samples and the models of the local steps, and is the largest consensus size of a minimal-sample model so far. The local step returns a model with at least as many inliers as its input, because it starts from the input and replaces it only by a model with more inliers; so . The loop ends after at most rounds, since and grows by 1. The guarantee of RANSAC carries over: the local step only increases , so any sample that would make RANSAC succeed also makes LO-RANSAC succeed, and the stopping rule still uses the inlier ratio of a model that was evaluated. That the local step brings the number of samples close to the formula is a benchmark result of Chum, Matas and Kittler, not a theorem. The proof is below.
Proof: LO-RANSAC keeps the model with most inliers it evaluates, never trails RANSAC on the same samples, and runs the local step about ln k timesfull
We use the notation of the page. , a round is one pass of lines L3 to L13, and "evaluated" means that of the model was compared with the best so far, either in line L7 or in a "try" of the local step. The minimal solver, the least squares solver and the residual are correct subroutines, and the model of computation is the real RAM.
Claim. (a) LOCAL-OPT returns a pair with . (b) At each test of line L2, is the largest over the models of the samples drawn so far, , and . (c) The loop ends after at most rounds. (d) Run RANSAC and LO-RANSAC on the same sequence of minimal samples. After each round, of LO-RANSAC is at least of RANSAC, and the value of of LO-RANSAC is at most that of RANSAC. (e) If the consensus sizes of the minimal-sample models of rounds are independent and identically distributed, the expected number of runs of the local step is at most the harmonic number .
Lemma 1. Part (a) holds.
Proof. Line L16 sets best to . Every later change of best, in line L17, in a try of line L23 and in the last try of line L26, replaces best by a pair only if is larger. So the size of the inlier set of best never decreases, and the returned pair is a model with its own inlier set.
Lemma 2. Part (b) holds.
Proof. At the start, , and no model is drawn. In a round with a model , line L8 compares with and line L9 raises if it is larger, so stays the largest size among the sample models. When is raised to , line L10 runs the local step on , and by Lemma 1 its result has at least inliers. Lines L11 and L12 then make , and they store a model together with its own inlier set. When is not raised, neither nor changes.
Lemma 3. Part (c) holds.
Proof. starts at and line L13 sets it only to values at most . Each round increases by 1, so after rounds the test of line L2 fails.
Proof of (d). After a round, the best set of RANSAC has the largest consensus size of the sample models so far, which is of LO-RANSAC on the same samples. By Lemma 2, for LO-RANSAC. Both algorithms set with , and this value does not increase in , as shown for RANSAC. A value of is only set when the best set grows, and of LO-RANSAC is at least that of RANSAC at all times, so its current is at most that of RANSAC. Hence on the same samples LO-RANSAC stops no later than RANSAC, and since its best set is never smaller, any run in which RANSAC finds a set of a given size is also a run in which LO-RANSAC does.
Proof of (e). The local step runs in round exactly when the size of the sample model is larger than all earlier sizes, a strict record. Let be independent and uniform on , independent of the , and order the pairs lexicographically. Every strict record of the sequence is a record of the pairs, because for all implies . The pairs are independent and identically distributed, and ties between them have probability 0, so all orders of the first pairs are equally likely, and the probability that the -th pair is the largest of the first is . By linearity of expectation, the expected number of records of the pairs is , and the expected number of strict records of the is at most . Finally .
Remark (assumptions of (e)). The sizes are independent and identically distributed when the samples are, and when the number of rounds is fixed in advance. With the adaptive stopping rule, the number of rounds depends on the sizes; the bound then holds for each fixed horizon , and the count of local steps up to round is at most in expectation. That the local step brings the number of samples close to the formula of the iteration bound is a benchmark result of Chum, Matas and Kittler (2003), not part of this proof.
Complexity
One round of the loop costs in the real RAM, as in RANSAC. One local step costs a fixed number of least squares fits and inlier counts, about of them, so for fixed parameters and a model type of fixed size. The local step runs once per strict record of the minimal-sample consensus sizes. If the sizes in rounds were independent with a continuous distribution, the expected number of records would be the harmonic number ; with integer sizes, which can tie, the number of strict records is at most that in expectation. Lebeda, Matas and Chum write the total time as , with the cost of a round and the cost of a local step. So the total time is , and the local steps add about times a constant factor of . Because is larger, is smaller than for RANSAC on noisy data.
For large inlier sets, the least squares fits of the local step can dominate. Lebeda, Matas and Chum limit the number of inliers used in these fits to 7 times the minimal sample size, drawn at random.
Properties
- Never worse than RANSAC on the same samples. For the same sequence of minimal samples, of LO-RANSAC is at least that of RANSAC at every round, so its is no larger and it stops no later (a theorem; see the proof).
- Few local steps. About in rounds under the assumption above.
- Better final model. The returned model is already a least squares fit, not a minimal-sample model, so no separate final refit is needed.
- Model-independent. The step needs only a least squares solver for the model, which most minimal problems have, for example the eight-point algorithm or the DLT for a homography.
Variants and improvements
- LO+. Lebeda, Matas and Chum (2012) score the models of the local step with the truncated quadratic cost of MSAC.
- Graph-cut RANSAC (Barath and Matas, 2018) replaces the local step by an energy minimization that also uses the spatial coherence of the inliers.
- MAGSAC++ uses an iteratively reweighted least squares step with weights marginalized over the noise scale, a local optimization without a fixed threshold.
- USAC (Raguram et al., 2013) includes local optimization as one stage, together with PROSAC sampling and early rejection of bad models.
When to use it
Use LO-RANSAC whenever the inliers are noisy and a least squares solver exists. The gain is largest for models with a larger minimal sample, such as the fundamental matrix from 7 or 8 matches, where a minimal sample of noisy inliers often gives a poor model. For exact data, as in the tests of this page with no noise, the local step changes nothing, and plain RANSAC is enough.
Pitfalls
- A local step that fits outliers. The wider threshold can include outliers near the model. The shrinking threshold of lines L22 to L25 removes them again; do not fit only at the wide threshold.
- Degenerate inlier sets. If all inliers are on a degenerate configuration, for example all matches on one plane for a fundamental matrix, the local step makes the wrong model more convincing. Check degeneracy before the local step.
- Cost on large inlier sets. Limit the number of items in each least squares fit, as Lebeda, Matas and Chum do.
Implementations
The Python code fits a line in the plane with . The function local_opt is the local step and can be tested alone. lo_ransac returns the number of local steps that ran, so the tests can check that it stays at most the number of rounds.
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/lo-ransac/. The authors are listed in prov/BQXMXZ.jsonl.
"""LO-RANSAC (locally optimized RANSAC), Chum, Matas and Kittler 2003,
with the local optimization of Lebeda, Matas and Chum 2012.
The RANSAC loop, plus a local optimization step that runs each time a model
from a minimal sample has more inliers than every earlier minimal-sample model.
The step refits on the inliers at a wider threshold, then several times draws a
larger non-minimal sample from the inliers, fits it by least squares and
iterates least squares while the threshold shrinks from m * eps to eps. The
best model of the step can replace the best model so far, and the number of
trials is updated from its inlier count. The model is a line in the plane,
a x + b y + c = 0 with a^2 + b^2 = 1, from s = 2 points; the least squares
fit is total least squares with unit weights (a choice of this code).
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
return canonical_line((a, b, -(a * x1 + b * y1)))
def canonical_line(line):
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):
"""Total least squares line through the points, or None if fewer than 2 or all equal."""
if len(points) < 2:
return None
m = len(points)
mx = sum(p[0] for p in points) / m
my = sum(p[1] for p in points) / m
sxx = sum((p[0] - mx) ** 2 for p in points)
syy = sum((p[1] - my) ** 2 for p in points)
sxy = sum((p[0] - mx) * (p[1] - my) for p in points)
if sxx == 0.0 and syy == 0.0:
return None
theta = 0.5 * math.atan2(2.0 * sxy, sxx - syy)
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."""
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 inliers(model, data, eps):
return [i for i, x in enumerate(data) if point_line_distance(model, x) <= eps]
def local_opt(model, inl, data, eps, rng, m_theta=math.sqrt(2.0), reps=10, iters=4, s_is=8):
"""Return (model, inliers) of the best model found by the local optimization."""
best, best_inl = model, inl # @line L16
cand = fit_line_lsq([data[i] for i in inliers(model, data, m_theta * eps)]) # @line L17
if cand is not None:
c_inl = inliers(cand, data, eps)
if len(c_inl) > len(best_inl):
best, best_inl = cand, c_inl
size = max(2, min(s_is, len(inl) // 2))
delta = (m_theta * eps - eps) / (iters - 1)
for _ in range(reps): # @line L18
sub = rng.sample(inl, min(size, len(inl))) # @line L19
cand = fit_line_lsq([data[i] for i in sub]) # @line L20
if cand is None:
continue
cand = fit_line_lsq([data[i] for i in inliers(cand, data, eps)]) or cand # @line L21
thr = m_theta * eps
for _ in range(iters): # @line L22
c_inl = inliers(cand, data, eps) # @line L23
if len(c_inl) > len(best_inl):
best, best_inl = cand, c_inl
nxt = fit_line_lsq([data[i] for i in inliers(cand, data, thr)]) # @line L24
if nxt is None:
break
cand = nxt
thr -= delta # @line L25
c_inl = inliers(cand, data, eps)
if len(c_inl) > len(best_inl):
best, best_inl = cand, c_inl
return best, best_inl # @line L26
def lo_ransac(data, eps, rng=None, s=2, p=0.99, max_trials=10000, **lo_args):
"""Return (model, inliers, trials, lo_runs)."""
rng = rng if rng is not None else random.Random()
n = len(data)
if n < s:
return None, [], 0, 0
lo_runs = 0
best, best_inl, n_s, k, t = None, [], 0, max_trials, 0 # @line L1
while t < k: # @line L2
t += 1 # @line L3
idx = rng.sample(range(n), s) # @line L4
theta = line_through([data[i] for i in idx]) # @line L5
if theta is None: # @line L6
continue
inl = inliers(theta, data, eps) # @line L7
if len(inl) > n_s: # @line L8
n_s = len(inl) # @line L9
lo_runs += 1
lo_model, lo_inl = local_opt(theta, inl, data, eps, rng, **lo_args) # @line L10
if len(lo_inl) > len(best_inl): # @line L11
best, best_inl = lo_model, lo_inl # @line L12
k = min(max_trials, ransac_trials(p, len(best_inl) / n, s)) # @line L13
if best is None: # @line L14
return None, [], t, lo_runs
return best, best_inl, t, lo_runs # @line L15
test_lo_ransac.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lo-ransac/. The authors are listed in prov/BQXMXZ.jsonl.
import itertools
import math
import random
from lo_ransac import fit_line_lsq, inliers, line_through, lo_ransac, local_opt, point_line_distance, ransac_trials
YS = [0.05, -0.05, 0.04, -0.03, 0.0, 0.05, -0.05, 0.02, -0.04, 0.03]
EXAMPLE = [(float(x), y) for x, y in enumerate(YS)] + [(2.0, 3.0), (5.0, -2.0), (7.0, 4.0), (8.0, -3.0)]
def planted(rng, n_in, n_out, sigma, a=0.5, b=2.0, gap=1.0):
pts = []
for _ in range(n_in):
x = rng.uniform(0.0, 10.0)
pts.append((x, a * x + b + rng.gauss(0.0, sigma)))
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 test_example_local_step():
line = line_through([EXAMPLE[3], EXAMPLE[4]])
inl = inliers(line, EXAMPLE, 0.08)
assert inl == [1, 3, 4, 5, 7]
wide = inliers(line, EXAMPLE, math.sqrt(2.0) * 0.08)
assert wide == [1, 2, 3, 4, 5, 6, 7]
refit = fit_line_lsq([EXAMPLE[i] for i in wide])
assert inliers(refit, EXAMPLE, 0.08) == list(range(10))
_, lo_inl = local_opt(line, inl, EXAMPLE, 0.08, random.Random(0))
assert lo_inl == list(range(10))
assert ransac_trials(0.99, 5 / 14, 2) == 34 and ransac_trials(0.99, 10 / 14, 2) == 7
def test_example_pairs():
counts = [len(inliers(line_through([EXAMPLE[i], EXAMPLE[j]]), EXAMPLE, 0.08))
for i, j in itertools.combinations(range(14), 2)]
assert len(counts) == 91 and counts.count(10) == 4 and max(counts) == 10
def test_example_run():
model, inl, t, runs = lo_ransac(EXAMPLE, 0.08, random.Random(1))
assert inl == list(range(10)) and t == 7 and 1 <= runs <= t
assert max(point_line_distance(model, EXAMPLE[i]) for i in inl) <= 0.08
def test_local_opt_never_loses():
for seed in range(5):
rng = random.Random(seed)
data, _ = planted(rng, 40, 30, sigma=0.1, gap=0.5)
for _ in range(10):
i, j = rng.sample(range(len(data)), 2)
line = line_through([data[i], data[j]])
inl = inliers(line, data, 0.25)
_, lo_inl = local_opt(line, inl, data, 0.25, random.Random(seed))
assert len(lo_inl) >= len(inl)
assert lo_inl == sorted(lo_inl)
def test_noisy_data():
for seed in range(4):
data, true_line = planted(random.Random(20 + seed), 25, 15, sigma=0.1, gap=0.6)
model, inl, t, runs = lo_ransac(data, 0.25, random.Random(seed))
assert all(i < 25 for i in inl) and len(inl) >= 23
assert runs <= t
a = math.atan2(abs(model[0] * true_line[1] - model[1] * true_line[0]),
abs(model[0] * true_line[0] + model[1] * true_line[1]))
assert a < math.radians(2.0)
def test_degenerate():
assert lo_ransac([(1.0, 1.0)] * 4, 0.1, random.Random(0), max_trials=10) == (None, [], 10, 0)
assert lo_ransac([(0.0, 0.0)], 0.1, random.Random(0)) == (None, [], 0, 0)
History
Chum, Matas and Kittler presented LO-RANSAC at the DAGM symposium in 2003. They observed that the number of samples RANSAC needs in practice is higher than the formula predicts, because a minimal sample of inliers does not always give a model with all inliers, and that a local optimization of each new best model closes the gap. Lebeda, Matas and Chum revisited the method in 2012 under the title "Fixing the locally optimized RANSAC". They gave the inner RANSAC with iterated least squares, the limit on the number of inliers in each fit and the truncated quadratic cost. Local optimization became a standard stage of USAC (2013) and of later methods such as Graph-cut RANSAC and MAGSAC++.
References
- Ondrej Chum, Jiri Matas and Josef Kittler, Locally optimized RANSAC, Pattern Recognition, DAGM 2003, Lecture Notes in Computer Science 2781, 236-243, The observation that the number of samples is higher than predicted, and the local optimization step applied to each new best model
- Karel Lebeda, Jiri Matas and Ondrej Chum, Fixing the locally optimized RANSAC, British Machine Vision Conference 2012, Algorithm 1 (when the local optimization runs), Algorithm 2 (the inner RANSAC on non-minimal samples), Algorithm 3 (iterated least squares with a shrinking threshold), Table 1 (parameter values) and the bound on the running time
- 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, Local optimization as one 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 BQXMXZ Edit this page History Report an error Markdown