Algorithm Search⌘K

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.

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
Properties
randomizednot exactofflineiterative
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 ln⁡k\ln k times in kk 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 D={x1,…,xn}D = \{x_1, \ldots, x_n\}, a minimal solver for samples of ss items, a residual r(θ,x)r(\theta, x), a threshold ε\varepsilon, a confidence pp and a cap kmax⁡k_{\max}. 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 mθ>1m_\theta > 1 for a wider threshold, a number of repetitions, a number of inner iterations and a size siss_{\text{is}} of the non-minimal samples. The goal is a model with a large consensus set I(θ)={x:r(θ,x)≤ε}I(\theta) = \{x : r(\theta, x) \le \varepsilon\}.

The algorithm

  1. LO-RANSAC(D, s, ε, p, k_max) ▷ n = |D|
  2. 1θ* ← none, I* ← ∅, n_s ← 0, 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 ← I(θ)
  9. 8if |I| > n_s then ▷ best minimal-sample model so far
  10. 9n_s ← |I|
  11. 10(θ_L, I_L) ← LOCAL-OPT(θ, I)
  12. 11if |I_L| > |I*| then
  13. 12θ* ← θ_L, I* ← I_L
  14. 13k ← min(k_max, ⌈log(1 − p) / log(1 − (|I*|/n)^s)⌉)
  15. 14if θ* is none then return failure
  16. 15return θ*, I*
  17. LOCAL-OPT(θ, I) ▷ keeps the model with most inliers at ε
  18. 16best ← (θ, I)
  19. 17try FIT-LSQ({x : r(θ, x) ≤ m_θ ε})
  20. 18repeat reps times
  21. 19S ← min(s_is, ⌊|I|/2⌋) items of I, drawn at random (at least s)
  22. 20θ' ← FIT-LSQ(S)
  23. 21θ' ← FIT-LSQ(I(θ')), ε' ← m_θ ε
  24. 22repeat iters times
  25. 23try θ'
  26. 24θ' ← FIT-LSQ({x : r(θ', x) ≤ ε'})
  27. 25ε' ← ε' − (m_θ ε − ε)/(iters − 1)
  28. 26return best, after a last try of θ'

Here "try θ′\theta'" means: compute I(θ′)I(\theta') 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 mθεm_\theta \varepsilon to ε\varepsilon. Their Table 1 gives mθ=2m_\theta = \sqrt 2, 10 repetitions, 4 iterations and sis=12s_{\text{is}} = 12 for homographies and 14 for epipolar geometry; the code uses the same values except sis=8s_{\text{is}} = 8 for a line. Their Algorithm 3 also weights the items; the code uses unit weights.

Example

Take 14 points: the 10 inliers (x,yx)(x, y_x) for x=0,1,…,9x = 0, 1, \ldots, 9 with y=0.05,−0.05,0.04,−0.03,0,0.05,−0.05,0.02,−0.04,0.03y = 0.05, -0.05, 0.04, -0.03, 0, 0.05, -0.05, 0.02, -0.04, 0.03, which lie near y=0y = 0, and the 4 outliers (2,3),(5,−2),(7,4),(8,−3)(2,3), (5,-2), (7,4), (8,-3). Use ε=0.08\varepsilon = 0.08, p=0.99p = 0.99 and mθ=2m_\theta = \sqrt 2, so the wide threshold is about 0.113.

The sample (3,−0.03),(4,0)(3, -0.03), (4, 0) gives the line y=0.03x−0.12y = 0.03x - 0.12, which tilts across the band. Its inliers at ε\varepsilon are the 5 points with x=1,3,4,5,7x = 1, 3, 4, 5, 7, so plain RANSAC would set k=⌈log⁡0.01/log⁡(1−(5/14)2)⌉=34k = \lceil \log 0.01 / \log(1 - (5/14)^2) \rceil = 34.

LO-RANSAC runs the local step. Line L17 takes the 7 points within 0.113 of the line, x=1,…,7x = 1, \ldots, 7, and fits them by least squares. The new line is about y=0.0039x−0.019y = 0.0039x - 0.019, and all 10 inliers are within 0.08 of it. The best model now has 10 inliers, and line L13 sets k=⌈log⁡0.01/log⁡(1−(10/14)2)⌉=7k = \lceil \log 0.01 / \log(1 - (10/14)^2) \rceil = 7.

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 x={4,7},{4,8},{4,9},{7,9}x = \{4, 7\}, \{4, 8\}, \{4, 9\}, \{7, 9\}, 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: I∗I^* has the most inliers among all models evaluated so far, both the models of the samples and the models of the local steps, and nsn_s 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 ∣I∗∣≥ns|I^*| \ge n_s. The loop ends after at most kmax⁡k_{\max} rounds, since k≤kmax⁡k \le k_{\max} and tt grows by 1. The guarantee of RANSAC carries over: the local step only increases ∣I∗∣|I^*|, 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. I(θ)={x∈D:r(θ,x)≤ε}I(\theta) = \{x \in D : r(\theta, x) \le \varepsilon\}, a round is one pass of lines L3 to L13, and "evaluated" means that I(⋅)I(\cdot) 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(θ,I(θ))(\theta, I(\theta)) returns a pair (θL,I(θL))(\theta_L, I(\theta_L)) with ∣I(θL)∣≥∣I(θ)∣|I(\theta_L)| \ge |I(\theta)|. (b) At each test of line L2, nsn_s is the largest ∣I(θ)∣|I(\theta)| over the models of the samples drawn so far, I∗=I(θ∗)I^* = I(\theta^*), and ∣I∗∣≥ns|I^*| \ge n_s. (c) The loop ends after at most kmax⁡k_{\max} rounds. (d) Run RANSAC and LO-RANSAC on the same sequence of minimal samples. After each round, ∣I∗∣|I^*| of LO-RANSAC is at least ∣I∗∣|I^*| of RANSAC, and the value of kk of LO-RANSAC is at most that of RANSAC. (e) If the consensus sizes of the minimal-sample models of kk rounds are independent and identically distributed, the expected number of runs of the local step is at most the harmonic number Hk=∑j=1k1/j≤1+ln⁡kH_k = \sum_{j=1}^k 1/j \le 1 + \ln k.

Lemma 1. Part (a) holds.

Proof. Line L16 sets best to (θ,I(θ))(\theta, I(\theta)). 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 (θ′,I(θ′))(\theta', I(\theta')) only if ∣I(θ′)∣|I(\theta')| 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. □\square

Lemma 2. Part (b) holds.

Proof. At the start, ns=0n_s = 0, I∗=∅I^* = \emptyset and no model is drawn. In a round with a model θ\theta, line L8 compares ∣I(θ)∣|I(\theta)| with nsn_s and line L9 raises nsn_s if it is larger, so nsn_s stays the largest size among the sample models. When nsn_s is raised to ∣I(θ)∣|I(\theta)|, line L10 runs the local step on θ\theta, and by Lemma 1 its result has at least ∣I(θ)∣=ns|I(\theta)| = n_s inliers. Lines L11 and L12 then make ∣I∗∣≥ns|I^*| \ge n_s, and they store a model together with its own inlier set. When nsn_s is not raised, neither nsn_s nor I∗I^* changes. □\square

Lemma 3. Part (c) holds.

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

Proof of (d). After a round, the best set of RANSAC has the largest consensus size of the sample models so far, which is nsn_s of LO-RANSAC on the same samples. By Lemma 2, ∣I∗∣≥ns|I^*| \ge n_s for LO-RANSAC. Both algorithms set k=min⁡(kmax⁡,⌈log⁡(1−p)/log⁡(1−ws)⌉)k = \min(k_{\max}, \lceil \log(1 - p) / \log(1 - w^s) \rceil) with w=∣I∗∣/nw = |I^*|/n, and this value does not increase in ww, as shown for RANSAC. A value of kk is only set when the best set grows, and ∣I∗∣|I^*| of LO-RANSAC is at least that of RANSAC at all times, so its current kk 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. □\square

Proof of (e). The local step runs in round jj exactly when the size XjX_j of the sample model is larger than all earlier sizes, a strict record. Let U1,…,UkU_1, \ldots, U_k be independent and uniform on (0,1)(0, 1), independent of the XjX_j, and order the pairs (Xj,Uj)(X_j, U_j) lexicographically. Every strict record of the sequence XjX_j is a record of the pairs, because Xj>XiX_j > X_i for all i<ji < j implies (Xj,Uj)>(Xi,Ui)(X_j, U_j) > (X_i, U_i). The pairs are independent and identically distributed, and ties between them have probability 0, so all j!j! orders of the first jj pairs are equally likely, and the probability that the jj-th pair is the largest of the first jj is 1/j1/j. By linearity of expectation, the expected number of records of the pairs is HkH_k, and the expected number of strict records of the XjX_j is at most HkH_k. Finally Hk≤1+∫1kdx/x=1+ln⁡kH_k \le 1 + \int_1^k dx/x = 1 + \ln k. □\square

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 kk, and the count of local steps up to round kk is at most HkH_k 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 Θ(n)\Theta(n) in the real RAM, as in RANSAC. One local step costs a fixed number of least squares fits and inlier counts, about reps⋅(iters+2)\text{reps} \cdot (\text{iters} + 2) of them, so Θ(n)\Theta(n) 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 kk rounds were independent with a continuous distribution, the expected number of records would be the harmonic number Hk≈ln⁡kH_k \approx \ln k; 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 CRk+CLO⌈log⁡k⌉C_R k + C_{LO} \lceil \log k \rceil, with CRC_R the cost of a round and CLOC_{LO} the cost of a local step. So the total time is Θ(kn)\Theta(k n), and the local steps add about ln⁡k\ln k times a constant factor of nn. Because ∣I∗∣|I^*| is larger, kk 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, ∣I∗∣|I^*| of LO-RANSAC is at least that of RANSAC at every round, so its kk is no larger and it stops no later (a theorem; see the proof).
  • Few local steps. About ln⁡k\ln k in kk 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 mθεm_\theta \varepsilon 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 s=2s = 2. 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.

lo_ransac.pyI0RawGitHub
# 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

  1. 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
  2. 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
  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, 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.

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