Algorithm Search⌘K

Algorithmadvanced

MLESAC

Also called maximum likelihood estimation sample consensus.

RANSAC that scores each model by the likelihood of a mixture of Gaussian inliers and uniform outliers; for each model, EM estimates only the mixing weight.

Time
Θ(k m n) worst · average · best
Space
Θ(n) extra
Where
k = the number of samples drawn, at most a set cap; m = the number of EM steps for each model; n = the number of data items
Properties
randomizednot exactofflineiterative
Origin
Philip H. S. Torr, Andrew Zisserman, 2000

MLESAC (maximum likelihood estimation sample consensus) is a variant of RANSAC that scores a model by a likelihood instead of an inlier count. It models the residual of an item as a mixture: with probability γ\gamma the item is an inlier, and its residual is Gaussian with a known standard deviation σ\sigma; with probability 1−γ1 - \gamma it is an outlier, and its residual is uniform on a range of size vv. For each model from a minimal sample, a few steps of expectation maximization estimate the mixing weight γ\gamma, and nothing else, because the model itself is fixed by the sample. The model of largest likelihood wins. Torr and Zisserman (2000) introduced MLESAC together with MSAC, which uses a truncated quadratic instead.

In plain words

RANSAC and MSAC need a hard limit that splits points into good and bad. MLESAC uses a softer rule. It says: a good point is near the guess, with small errors much more likely than large ones; a bad point can be anywhere in the picture with the same chance. Each point then gets a degree of belief that it is good.

Before a guess can be scored, MLESAC must know what fraction of the points are good. It does not know, so it starts at one half and improves the fraction a few times: it computes the belief of each point and takes their average as the new fraction.

The score of the guess is how well this mix of good and bad points explains all the points at once. The guess with the best score wins.

The problem

The input is 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), the inlier noise σ\sigma, the size vv of the range of outlier residuals, a confidence pp, a cap kmax⁡k_{\max} and a number mm of EM steps. With ϕσ(e)=exp⁡(−e2/2σ2)/(2π σ)\phi_\sigma(e) = \exp(-e^2/2\sigma^2) / (\sqrt{2\pi}\,\sigma), the negative log-likelihood of a model with mixing weight γ\gamma is

L(θ,γ)=−∑i=1nlog⁡(γ ϕσ(r(θ,xi))+1−γv).L(\theta, \gamma) = -\sum_{i=1}^{n} \log\Big(\gamma\, \phi_\sigma\big(r(\theta, x_i)\big) + \frac{1 - \gamma}{v}\Big).

The goal is a model of small min⁡γL(θ,γ)\min_\gamma L(\theta, \gamma). MLESAC searches only the models of minimal samples, so it is a randomized heuristic for this goal, a case of robust model fitting by maximum likelihood.

The algorithm

  1. MLESAC(D, s, σ, v, p, k_max, m) ▷ n = |D|
  2. 1θ* ← none, L* ← ∞, γ* ← 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. 7g_i ← φ_σ(r(θ, x_i)) for i = 1, …, n
  9. 8γ ← 1/2
  10. 9repeat m times
  11. 10z_i ← γ g_i / (γ g_i + (1 − γ)/v) for i = 1, …, n
  12. 11γ ← (1/n) Σ_i z_i
  13. 12L ← − Σ_i log(γ g_i + (1 − γ)/v)
  14. 13if L < L* then
  15. 14θ* ← θ, L* ← L, γ* ← γ
  16. 15k ← min(k_max, ⌈log(1 − p) / log(1 − γ^s)⌉)
  17. 16if θ* is none then return failure
  18. 17θ ← weighted least squares on D with the weights z_i of θ* and γ*
  19. 18return θ, γ*, L*

Lines L8 to L11 are EM for one unknown. The E step of line L10 computes ziz_i, the posterior probability that item ii is an inlier. The M step of line L11 sets γ\gamma to their mean. The model θ\theta stays fixed: EM here does not refit the model, it only estimates the inlier fraction for the model at hand. Line L15 is the adaptive rule of RANSAC with γ\gamma as the inlier ratio. Line L17 is a final refit; the code uses a weighted least squares fit with the weights ziz_i, a choice of this code.

Example

Take the 7 points (0,0),(1,0.1),(2,0),(3,0.1),(4,0),(1,2),(3,−2)(0,0), (1,0.1), (2,0), (3,0.1), (4,0), (1,2), (3,-2), lines with s=2s = 2, the point-to-line distance, σ=0.1\sigma = 0.1, v=10v = 10 and m=5m = 5. Three samples:

tt sample line γ\gamma after 1 step γ\gamma after 5 steps LL
1 (1,0.1),(3,0.1)(1,0.1), (3,0.1) y=0.1y = 0.1 0.6903 0.7040 3.3040
2 (2,0),(1,2)(2,0), (1,2) 2x+y=42x + y = 4 0.4181 0.4139 9.7382
3 (0,0),(4,0)(0,0), (4,0) y=0y = 0 0.6925 0.7050 2.8107

The slanted line passes exactly through 3 of the 7 points, and EM gives it γ≈0.41\gamma \approx 0.41, a little below 3/7≈0.433/7 \approx 0.43, because the other points are far. The lines y=0.1y = 0.1 and y=0y = 0 both have five close points, but y=0y = 0 is closer to them, so its likelihood is larger and LL is smaller: MLESAC prefers y=0y = 0, as MSAC does. With γ=0.705\gamma = 0.705, line L15 gives ⌈log⁡0.01/log⁡(1−0.7052)⌉=7\lceil \log 0.01 / \log(1 - 0.705^2) \rceil = 7 rounds. The weighted refit gives the line y=0.0398y = 0.0398; the weights of the two outliers are almost 0.

Correctness

MLESAC keeps an invariant at line L2: θ∗\theta^* has the least value of LL among the models of the samples drawn so far, where LL is computed with the γ\gamma of mm EM steps from 1/21/2. The loop ends after at most kmax⁡k_{\max} rounds. For a fixed model, ℓ(γ)=−L(θ,γ)\ell(\gamma) = -L(\theta, \gamma) is concave in γ\gamma, and one EM step is γ′=γ+γ(1−γ) ℓ′(γ)/n\gamma' = \gamma + \gamma(1 - \gamma)\,\ell'(\gamma)/n, which never decreases ℓ\ell (the ascent property of EM). So more EM steps only make the score of a model better, and a fixed point inside (0,1)(0, 1) is the maximum likelihood weight. The guarantee of the sampling part is the same as for MSAC: if the model of least score is the model of every sample in its inlier set, a run of KK rounds finds it with probability at least 1−(1−q)K1 - (1 - q)^K. The stopping rule with γ\gamma is a heuristic. The proof is below.

Proof: The EM step of MLESAC never lowers the likelihood, and MLESAC keeps the sampled model of best scorefull

We use the notation of the page. For a fixed model θ\theta, write ai=ϕσ(r(θ,xi))>0a_i = \phi_\sigma(r(\theta, x_i)) > 0 and b=1/v>0b = 1/v > 0, and let Di(γ)=γai+(1−γ)bD_i(\gamma) = \gamma a_i + (1 - \gamma) b and ℓ(γ)=∑i=1nlog⁡Di(γ)=−L(θ,γ)\ell(\gamma) = \sum_{i=1}^n \log D_i(\gamma) = -L(\theta, \gamma) for γ∈[0,1]\gamma \in [0, 1]. The model of computation is the real RAM with exp⁡\exp and log⁡\log as exact operations.

Claim. (a) ℓ\ell is concave on [0,1][0, 1]. (b) For 0<γ<10 < \gamma < 1, the EM step of lines L10 and L11, γ′=1n∑iγai/Di(γ)\gamma' = \frac{1}{n} \sum_i \gamma a_i / D_i(\gamma), satisfies 0<γ′<10 < \gamma' < 1, γ′=γ+γ(1−γ)ℓ′(γ)/n\gamma' = \gamma + \gamma (1 - \gamma) \ell'(\gamma) / n and ℓ(γ′)≥ℓ(γ)\ell(\gamma') \ge \ell(\gamma). A γ∈(0,1)\gamma \in (0, 1) is a fixed point of the step if and only if it maximizes ℓ\ell on [0,1][0, 1]. (c) At each test of line L2, θ∗\theta^* has the least score LL among the models of the samples drawn so far, where each score uses the γ\gamma of mm EM steps from 1/21/2, and the loop ends after at most kmax⁡k_{\max} rounds.

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

Proof. DiD_i is affine in γ\gamma and positive on [0,1][0, 1], so ℓ′′(γ)=−∑i(ai−b)2/Di(γ)2≤0\ell''(\gamma) = -\sum_i (a_i - b)^2 / D_i(\gamma)^2 \le 0. □\square

Lemma 2 (the step as a gradient step). For 0<γ<10 < \gamma < 1, γ′−γ=γ(1−γ)ℓ′(γ)/n\gamma' - \gamma = \gamma (1 - \gamma) \ell'(\gamma) / n, and 0<γ′<10 < \gamma' < 1.

Proof. γai−γDi(γ)=γ(1−γ)(ai−b)\gamma a_i - \gamma D_i(\gamma) = \gamma (1 - \gamma)(a_i - b), so γ′−γ=1n∑iγai−γDi(γ)Di(γ)=γ(1−γ)n∑iai−bDi(γ)\gamma' - \gamma = \frac{1}{n} \sum_i \frac{\gamma a_i - \gamma D_i(\gamma)}{D_i(\gamma)} = \frac{\gamma (1 - \gamma)}{n} \sum_i \frac{a_i - b}{D_i(\gamma)}, and the sum is ℓ′(γ)\ell'(\gamma). Each posterior zi=γai/Di(γ)z_i = \gamma a_i / D_i(\gamma) lies strictly between 0 and 1 because γai>0\gamma a_i > 0 and (1−γ)b>0(1 - \gamma) b > 0, so their mean γ′\gamma' does too. □\square

Lemma 3 (ascent). For 0<γ<10 < \gamma < 1, ℓ(γ′)−ℓ(γ)≥n(γ′log⁡γ′γ+(1−γ′)log⁡1−γ′1−γ)≥0\ell(\gamma') - \ell(\gamma) \ge n \big(\gamma' \log \frac{\gamma'}{\gamma} + (1 - \gamma') \log \frac{1 - \gamma'}{1 - \gamma}\big) \ge 0.

Proof. With zi=γai/Di(γ)z_i = \gamma a_i / D_i(\gamma) and 1−zi=(1−γ)b/Di(γ)1 - z_i = (1 - \gamma) b / D_i(\gamma),

Di(γ′)Di(γ)=ziγ′γ+(1−zi)1−γ′1−γ.\frac{D_i(\gamma')}{D_i(\gamma)} = z_i \frac{\gamma'}{\gamma} + (1 - z_i) \frac{1 - \gamma'}{1 - \gamma}.

The logarithm is concave, so by Jensen's inequality with the weights ziz_i and 1−zi1 - z_i, log⁡Di(γ′)Di(γ)≥zilog⁡γ′γ+(1−zi)log⁡1−γ′1−γ\log \frac{D_i(\gamma')}{D_i(\gamma)} \ge z_i \log \frac{\gamma'}{\gamma} + (1 - z_i) \log \frac{1 - \gamma'}{1 - \gamma}. Summing over ii and using ∑izi=nγ′\sum_i z_i = n \gamma' gives the first inequality. The right side is nn times the Kullback-Leibler divergence between the Bernoulli laws with parameters γ′\gamma' and γ\gamma, which is nonnegative by Gibbs' inequality. □\square

Lemma 4 (fixed points). A γ∈(0,1)\gamma \in (0, 1) is a fixed point of the step if and only if it maximizes ℓ\ell on [0,1][0, 1].

Proof. By Lemma 2, γ′=γ\gamma' = \gamma if and only if ℓ′(γ)=0\ell'(\gamma) = 0, since γ(1−γ)>0\gamma (1 - \gamma) > 0. By Lemma 1, ℓ\ell is concave, so an interior point with ℓ′(γ)=0\ell'(\gamma) = 0 is a maximum on [0,1][0, 1], and an interior maximum has ℓ′(γ)=0\ell'(\gamma) = 0. □\square

Lemmas 2 to 4 prove (b). Lines L8 to L11 start at γ=1/2\gamma = 1/2 and apply the step mm times, so by Lemma 2 every value stays in (0,1)(0, 1) and by Lemma 3 the likelihood does not decrease along the way.

Proof of (c). Before the first round, L∗=∞L^* = \infty. In a round, either line L6 skips the sample and nothing changes, or line L12 computes the score LL of the new model with its own γ\gamma. Line L13 replaces θ∗\theta^* exactly when L<L∗L < L^*, so after line L14 L∗L^* is the least score among the old models and the new one. The value kk starts at kmax⁡k_{\max} and line L15 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

Remark (sampling). If a model of least score is the model of every sample inside its set of likely inliers II, and the samples are independent, then KK rounds find it with probability at least 1−(1−q)K1 - (1 - q)^K, where qq is the probability that a sample lies in II, by the argument for MSAC. The count of line L15 uses the estimate γ\gamma of the best model so far, which is not a bound on the inlier ratio of the best model overall, so the stopping rule is a heuristic.

Complexity

One round costs the minimal solver, O(1)O(1) for a fixed model type, then nn densities in line L7, mm EM steps of Θ(n)\Theta(n) each and one sum of nn logarithms, so Θ(mn)\Theta(m n) in the real RAM with exp⁡\exp and log⁡\log as unit-cost operations. With kk rounds the time is Θ(kmn)\Theta(k m n), against Θ(kn)\Theta(k n) for RANSAC and MSAC. With a small fixed mm, the cost per round is a constant factor more than MSAC. The extra space is Θ(n)\Theta(n). The number of rounds kk is random, at most kmax⁡k_{\max}, and follows the iteration bound with γ\gamma in place of the inlier ratio.

Properties

  • Soft inliers. Each item has a posterior inlier probability ziz_i instead of a yes or no label.
  • Two parameters instead of a threshold. MLESAC needs σ\sigma and vv. An implicit threshold remains: an item is more likely an inlier than an outlier when γ ϕσ(e)>(1−γ)/v\gamma\,\phi_\sigma(e) > (1 - \gamma)/v.
  • EM estimates only γ\gamma. The model is the model of the sample. The EM is a one-dimensional fit, cheap and with a unique optimum, since the log-likelihood is concave in γ\gamma (a theorem).
  • Bounded influence. A far outlier adds about −log⁡((1−γ)/v)-\log((1 - \gamma)/v) to LL whatever its residual is, so, as for MSAC, its influence has a ceiling.
  • Accuracy. Torr and Zisserman report that MLESAC gives more accurate fundamental matrices than RANSAC in their experiments (a benchmark result).

Variants and improvements

  • MSAC is the cheaper relative: a truncated quadratic cost with no EM. Each round costs one pass over the data.
  • Guided MLESAC. Tordoff and Murray (2002) use the match scores of the feature matcher as prior inlier probabilities, both to choose the samples and in the mixture. PROSAC uses the ordering of the scores instead of their values.
  • MAGSAC keeps a likelihood view but removes the fixed σ\sigma by marginalizing over it.
  • LO-RANSAC adds local optimization of the best model, which works with any of these scores.
  • More EM. One can run EM over both γ\gamma and the model, which turns the last step into an iteratively reweighted fit, as in the iteratively reweighted least squares step of MAGSAC++.

When to use it

Use MLESAC when the inlier noise σ\sigma is known well, the outliers spread over a known range, and an accurate score matters more than a few EM steps per model. If the outlier range vv is not known, or the speed of each round matters, use MSAC. If σ\sigma is not known well, use MAGSAC.

Pitfalls

  • The wrong vv. The implicit threshold falls as the outlier density 1/v1/v grows. If vv is too small, true inliers with moderate residuals are explained as outliers. If vv is too large, outliers near the model are explained as inliers. Set vv from the range of residuals that are possible, for example the size of the search window in pixels.
  • Numerical underflow. For large residuals ϕσ(e)\phi_\sigma(e) underflows to 0. The mixture term (1−γ)/v(1 - \gamma)/v keeps the logarithm finite, so do not drop it, and do not compute the log of the Gaussian term alone.
  • EM from a bad start. The concavity makes the start harmless in the limit, but with few EM steps the estimate of γ\gamma is not converged. Use the same mm for all models so that their scores are comparable.
  • γ\gamma for stopping. γ\gamma is an estimate of the inlier ratio for the best model so far, not a bound on the ratio of the best model overall, so the stopping rule is a heuristic.

Implementations

The Python code fits a line in the plane with s=2s = 2. The functions em_mixing and mixture_nll give the EM estimate of γ\gamma and the score of any model, and the tests use them to check the ascent of EM and the invariant on every sampled model.

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.

mlesac.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mlesac/. The authors are listed in prov/3GWPBP.jsonl.
"""MLESAC (maximum likelihood estimation sample consensus), Torr and Zisserman 2000.

The RANSAC loop with a likelihood score. A residual e has the mixture density
    gamma * N(e; 0, sigma^2) + (1 - gamma) / v,
Gaussian inliers with known sigma and uniform outliers on a range of size v.
For each hypothesis, a few EM steps from gamma = 1/2 estimate the mixing weight
gamma only; the model of least negative log-likelihood wins. The default model
is a line in the plane, a x + b y + c = 0 with a^2 + b^2 = 1, from s = 2 points.
The final model is a weighted least squares refit with the posterior inlier
probabilities as weights (a choice of this code). Standard library only.
Cost: O(k (C + m n)) for k trials, m EM steps and n data items.
"""

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_weighted(points, weights):
    """Weighted total least squares line, or None if the weights or the spread vanish."""
    sw = sum(weights)
    if len(points) < 2 or sw <= 0.0:
        return None
    mx = sum(w * p[0] for w, p in zip(weights, points)) / sw
    my = sum(w * p[1] for w, p in zip(weights, points)) / sw
    sxx = sum(w * (p[0] - mx) ** 2 for w, p in zip(weights, points))
    syy = sum(w * (p[1] - my) ** 2 for w, p in zip(weights, points))
    sxy = sum(w * (p[0] - mx) * (p[1] - my) for w, p in zip(weights, 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 gauss(e, sigma):
    return math.exp(-0.5 * (e / sigma) ** 2) / (math.sqrt(2.0 * math.pi) * sigma)


def mixture_nll(residuals, gamma, sigma, v):
    """Negative log-likelihood of the residuals under the mixture."""
    return -sum(math.log(gamma * gauss(e, sigma) + (1.0 - gamma) / v) for e in residuals)


def em_mixing(residuals, sigma, v, steps=5, gamma=0.5):
    """EM for the mixing weight only, from the given start, for a fixed number of steps."""
    g = [gauss(e, sigma) for e in residuals]
    u = 1.0 / v
    for _ in range(steps):
        gamma = sum(gamma * gi / (gamma * gi + (1.0 - gamma) * u) for gi in g) / len(g)
    return gamma


def mlesac(data, sigma, v, rng=None, s=2, p=0.99, max_trials=10000, em_steps=5,
           fit_minimal=line_through, residual=point_line_distance, refit=fit_line_weighted):
    """Return (model, gamma, nll, trials).

    nll is the negative log-likelihood of the best sampled model, gamma its
    estimated inlier fraction, and model the weighted refit with the posterior
    inlier probabilities (or the sampled model if the refit fails). Returns
    (None, 0.0, inf, trials) if no sample gives a model.
    """
    rng = rng if rng is not None else random.Random()
    n = len(data)
    if n < s:
        return None, 0.0, math.inf, 0
    u = 1.0 / v
    best, best_nll, best_gamma, k, t = None, math.inf, 0.0, max_trials, 0  # @line L1
    while t < k:  # @line L2
        t += 1  # @line L3
        idx = rng.sample(range(n), s)  # @line L4
        theta = fit_minimal([data[i] for i in idx])  # @line L5
        if theta is None:  # @line L6
            continue
        g = [gauss(residual(theta, x), sigma) for x in data]  # @line L7
        gamma = 0.5  # @line L8
        for _ in range(em_steps):  # @line L9
            z = [gamma * gi / (gamma * gi + (1.0 - gamma) * u) for gi in g]  # @line L10
            gamma = sum(z) / n  # @line L11
        nll = -sum(math.log(gamma * gi + (1.0 - gamma) * u) for gi in g)  # @line L12
        if nll < best_nll:  # @line L13
            best, best_nll, best_gamma = theta, nll, gamma  # @line L14
            k = min(max_trials, ransac_trials(p, gamma, s))  # @line L15
    if best is None:  # @line L16
        return None, 0.0, math.inf, t
    g = [gauss(residual(best, x), sigma) for x in data]  # @line L17
    z = [best_gamma * gi / (best_gamma * gi + (1.0 - best_gamma) * u) for gi in g]
    model = refit(data, z) if refit is not None else None
    return (model if model is not None else best), best_gamma, best_nll, t  # @line L18
test_mlesac.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mlesac/. The authors are listed in prov/3GWPBP.jsonl.

import math
import random

from mlesac import (em_mixing, fit_line_weighted, line_through, mixture_nll, mlesac,
                    point_line_distance, ransac_trials)

EXAMPLE = [(0, 0), (1, 0.1), (2, 0), (3, 0.1), (4, 0), (1, 2), (3, -2)]


def residuals(line, data):
    return [point_line_distance(line, x) for x in data]


def planted(rng, n_in, n_out, a=0.5, b=2.0, sigma=0.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) if sigma else 0.0)))
    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 line_angle(l1, l2):
    return math.atan2(abs(l1[0] * l2[1] - l1[1] * l2[0]), abs(l1[0] * l2[0] + l1[1] * l2[1]))


def best_gamma(e, sigma, v):
    """Ternary search; the log-likelihood is concave in gamma."""
    lo, hi = 0.0, 1.0
    for _ in range(200):
        a, b = lo + (hi - lo) / 3, hi - (hi - lo) / 3
        if mixture_nll(e, a, sigma, v) < mixture_nll(e, b, sigma, v):
            hi = b
        else:
            lo = a
    return lo


def test_example_values():
    y01 = residuals(line_through([(1, 0.1), (3, 0.1)]), EXAMPLE)
    slanted = residuals(line_through([(2, 0), (1, 2)]), EXAMPLE)
    y0 = residuals(line_through([(0, 0), (4, 0)]), EXAMPLE)
    expect = [(y01, 0.6903, 0.704, 3.304), (slanted, 0.4181, 0.4139, 9.7382), (y0, 0.6925, 0.705, 2.8107)]
    for e, g1, g5, nll in expect:
        assert abs(em_mixing(e, 0.1, 10.0, steps=1) - g1) < 5e-5
        g = em_mixing(e, 0.1, 10.0)
        assert abs(g - g5) < 5e-5
        assert abs(mixture_nll(e, g, 0.1, 10.0) - nll) < 5e-5
    assert ransac_trials(0.99, 0.705, 2) == 7


def test_example_run():
    model, gamma, nll, t = mlesac(EXAMPLE, 0.1, 10.0, random.Random(1))
    assert abs(nll - 2.8107) < 5e-5 and abs(gamma - 0.705) < 5e-5 and t == 7
    assert abs(model[0]) < 1e-12 and abs(model[2] + 0.0398) < 5e-5


def test_em_ascent_and_limit():
    data, line = planted(random.Random(4), 30, 20, sigma=0.1, gap=0.5)
    e = residuals(line, data)
    g, prev = 0.5, mixture_nll(e, 0.5, 0.1, 20.0)
    for _ in range(50):
        g = em_mixing(e, 0.1, 20.0, steps=1, gamma=g)
        cur = mixture_nll(e, g, 0.1, 20.0)
        assert cur <= prev + 1e-12
        prev = cur
    assert abs(g - best_gamma(e, 0.1, 20.0)) < 1e-6


def test_nll_is_least_among_sampled_models():
    for seed in range(3):
        data, _ = planted(random.Random(seed), 30, 30, sigma=0.05, gap=0.5)
        seen = []

        def solver(sample):
            line = line_through(sample)
            if line is not None:
                seen.append(mixture_nll(residuals(line, data), em_mixing(residuals(line, data), 0.05, 20.0),
                                        0.05, 20.0))
            return line

        _, _, nll, t = mlesac(data, 0.05, 20.0, random.Random(70 + seed), fit_minimal=solver)
        assert len(seen) == t
        assert abs(nll - min(seen)) < 1e-9


def test_planted_line():
    data, true_line = planted(random.Random(3), 50, 50, sigma=0.05, gap=0.5)
    model, gamma, _, _ = mlesac(data, 0.05, 20.0, random.Random(5))
    assert line_angle(model, true_line) < math.radians(1.0)
    assert abs(gamma - 0.5) < 0.1


def test_degenerate():
    assert mlesac([(1.0, 1.0)] * 4, 0.1, 10.0, random.Random(0), max_trials=10)[:3] == (None, 0.0, math.inf)
    assert mlesac([(0.0, 0.0)], 0.1, 10.0, random.Random(0)) == (None, 0.0, math.inf, 0)
    assert fit_line_weighted([(0.0, 0.0), (1.0, 1.0)], [0.0, 0.0]) is None

History

Torr and Zisserman published MLESAC in 2000 in Computer Vision and Image Understanding, for the estimation of the fundamental matrix and other image relations. They gave the mixture of a Gaussian and a uniform distribution for the errors, the EM estimate of the mixing weight and the MSAC cost as a cheaper alternative. Tordoff and Murray (2002) added guided sampling with prior inlier probabilities from the match scores. The likelihood view led to the marginalization over σ\sigma in MAGSAC (2019).

References

  1. Philip H. S. Torr and Andrew Zisserman, MLESAC: a new robust estimator with application to estimating image geometry, Computer Vision and Image Understanding 78(1), 2000, 138-156, The definition of MLESAC: the mixture model of the errors, the estimation of the mixing parameter by EM and the comparison with RANSAC and MSAC
  2. 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 MLESAC: match scores as prior inlier probabilities in the sampling and in the mixture
  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 part of the survey on model verification and the choice of the cost function

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