Algorithm Search⌘K

Algorithmadvanced

MSAC

Also called M-estimator sample consensus.

RANSAC that scores a model by a truncated quadratic cost of the residuals instead of the inlier count, so it prefers models that fit the inliers well.

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
Philip H. S. Torr, Andrew Zisserman, 2000

MSAC (M-estimator sample consensus) is a variant of RANSAC that changes only the score of a model. RANSAC counts the inliers, the items whose residual is at most a threshold TT, so all inliers count the same and a model that passes close to them does not beat a model that passes near the edge of the band. MSAC gives each item the cost min⁡(r2,T2)\min(r^2, T^2): an inlier pays its squared residual and an outlier pays the constant T2T^2. The model of least total cost wins. This is the truncated quadratic, a redescending M-estimator cost, which is where the name comes from. Torr and Zisserman (2000) introduced it together with MLESAC. The change costs nothing extra per item, and it makes the result less sensitive to the choice of TT.

In plain words

RANSAC asks each guess one question: how many points are close enough? Every close point gets one vote, whether it lies right on the guess or just inside the limit. So two guesses can tie even though one of them clearly fits better.

MSAC asks a finer question. Every close point adds a penalty equal to the square of its distance, so points right on the guess cost almost nothing. Every far point adds the same fixed penalty, the square of the limit, however far it is. The guess with the smallest total penalty wins. Far points still cannot pull the answer, because their penalty has a ceiling. Close points now say how well the guess fits them.

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 TT, a confidence pp and a cap kmax⁡k_{\max}. The goal is a model of small truncated quadratic cost

C(θ)=∑i=1nρ(r(θ,xi)),ρ(r)=min⁡(r2,T2).C(\theta) = \sum_{i=1}^{n} \rho\big(r(\theta, x_i)\big), \qquad \rho(r) = \min(r^2, T^2).

A model of least cost is a solution of robust model fitting with this M-estimator. MSAC searches only the models of minimal samples, so it is a randomized heuristic for this goal, as RANSAC is for maximum consensus.

The algorithm

  1. MSAC(D, s, T, p, k_max) ▷ n = |D|
  2. 1θ* ← none, C* ← ∞, I* ← ∅, 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. 7e_i ← r(θ, x_i)² for i = 1, …, n
  9. 8C ← Σ_i min(e_i, T²)
  10. 9if C < C* then
  11. 10θ* ← θ, C* ← C
  12. 11I* ← {x_i : e_i ≤ T²}
  13. 12k ← min(k_max, ⌈log(1 − p) / log(1 − (|I*|/n)^s)⌉)
  14. 13if θ* is none then return failure
  15. 14θ ← FIT-LEAST-SQUARES(I*)
  16. 15return θ, I*, C*

Lines L7 and L8 replace the inlier count of RANSAC. Line L12 is the adaptive stopping rule of RANSAC, with the inlier ratio of the model of least cost so far. Unlike in RANSAC, this ratio can drop when a better model has fewer inliers, so kk can grow again, but never above kmax⁡k_{\max}. Line L14 refits the model to the inliers of the best model, as in RANSAC.

The threshold TT is a design choice. For a residual of one dimension with Gaussian noise of standard deviation σ\sigma, a common choice is T2=3.84 σ2T^2 = 3.84\,\sigma^2, the 95 percent point of a chi-square variable with one degree of freedom (Hartley and Zisserman, Section 4.7).

Example

Take the 7 points (0,0),(1,0.1),(2,0),(3,0.1),(4,0)(0,0), (1,0.1), (2,0), (3,0.1), (4,0), which lie near y=0y = 0, and the outliers (1,2),(3,−2)(1,2), (3,-2). Use lines with s=2s = 2, the point-to-line distance, T=0.25T = 0.25 (so T2=0.0625T^2 = 0.0625) and p=0.99p = 0.99. Three samples:

tt sample line inliers cost CC C∗C^* kk
1 (1,0.1),(3,0.1)(1,0.1), (3,0.1) y=0.1y = 0.1 5 3(0.01)+2(0.0625)=0.1553(0.01) + 2(0.0625) = 0.155 0.155 7
2 (2,0),(1,2)(2,0), (1,2) 2x+y=42x + y = 4 3 0.250.25 0.155 7
3 (0,0),(4,0)(0,0), (4,0) y=0y = 0 5 2(0.01)+2(0.0625)=0.1452(0.01) + 2(0.0625) = 0.145 0.145 7

The line 2x+y=42x + y = 4 passes exactly through (2,0)(2,0) and both outliers, so its cost is 4T2=0.254 T^2 = 0.25. The lines y=0.1y = 0.1 and y=0y = 0 have the same five inliers. RANSAC sees a tie and keeps the first one, y=0.1y = 0.1. MSAC prefers y=0y = 0, because its inliers are closer. With w=5/7w = 5/7, the stopping rule gives ⌈log⁡0.01/log⁡(1−25/49)⌉=7\lceil \log 0.01 / \log(1 - 25/49) \rceil = 7. Over all 21 pairs of points, the least cost is 0.145, so no later sample can replace y=0y = 0, and the refit on the five inliers gives y=0.04y = 0.04, the mean height of the five points.

Correctness

MSAC keeps an invariant at line L2: θ∗\theta^* has the least cost among the models of the samples drawn so far, and C∗C^* is that cost. The loop ends after at most kmax⁡k_{\max} rounds, because tt grows by 1 in each round and line L12 never sets kk above kmax⁡k_{\max}. The probabilistic guarantee of RANSAC carries over in a weaker form. Suppose a model of least cost θmin⁡\theta_{\min} is the model of every sample inside its inlier set II, and the samples are independent. Then a run of at least KK rounds returns cost C(θmin⁡)C(\theta_{\min}) with probability at least 1−(1−q)K1 - (1 - q)^K, where qq is the probability that a sample lies in II. The stopping rule gives this count only if the best model so far has at least ∣I∣|I| inliers, which is not always true, so for MSAC the rule is a heuristic. The proof is below.

Proof: MSAC keeps the sampled model of least truncated quadratic cost and finds a least-cost model with high probability under the sampling assumptionsfull

We use the notation of the page. DD has nn items, a minimal sample has s≤ns \le n distinct items, ρ(r)=min⁡(r2,T2)\rho(r) = \min(r^2, T^2) and C(θ)=∑iρ(r(θ,xi))C(\theta) = \sum_i \rho(r(\theta, x_i)). The minimal solver, the residual and the refit are correct subroutines, and the model of computation is the real RAM.

Claim. (a) At each test of line L2, θ∗\theta^* has the least cost among the models of the samples drawn so far, C∗=C(θ∗)C^* = C(\theta^*), and I∗I^* is the set of items with r(θ∗,x)2≤T2r(\theta^*, x)^2 \le T^2; if no sample gave a model, C∗=∞C^* = \infty. (b) The loop ends after at most kmax⁡k_{\max} rounds. (c) Let θmin⁡\theta_{\min} be a model of least cost among all models the solver can return, let I={x:r(θmin⁡,x)≤T}I = \{x : r(\theta_{\min}, x) \le T\}, assume that every sample inside II gives the model θmin⁡\theta_{\min}, and that the samples are independent, and let qq be the probability that one sample is a subset of II. If the loop runs at least KK rounds, then C∗=C(θmin⁡)C^* = C(\theta_{\min}) at the end with probability at least 1−(1−q)K1 - (1 - q)^K.

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

Proof. Before the first round, no model is drawn and C∗=∞C^* = \infty. In a round, either line L6 skips the sample and nothing changes, or lines L7 and L8 compute C=C(θ)C = C(\theta) for the new model, since min⁡(ei,T2)=ρ(r(θ,xi))\min(e_i, T^2) = \rho(r(\theta, x_i)) when ei=r(θ,xi)2e_i = r(\theta, x_i)^2. Line L9 replaces θ∗\theta^* exactly when C<C∗C < C^*, so after line L10 C∗C^* is the least cost among the old models and the new one. Line L11 recomputes I∗I^* from the residuals of the new θ∗\theta^*, so I∗I^* belongs to θ∗\theta^*. □\square

Lemma 2 (termination). Part (b) holds.

Proof. kk starts at kmax⁡k_{\max}, and line L12 sets it only to values at most kmax⁡k_{\max}. The value of kk can go up or down, but each round increases tt by 1, so after kmax⁡k_{\max} rounds t≥kmax⁡≥kt \ge k_{\max} \ge k and the test of line L2 fails. □\square

Proof of (c). The samples are independent, so the probability that none of the first KK samples is a subset of II is (1−q)K(1 - q)^K. If one of them is a subset of II, it gives θmin⁡\theta_{\min} by assumption, and by Lemma 1 C∗≤C(θmin⁡)C^* \le C(\theta_{\min}) from that round on. No sampled model has a smaller cost than θmin⁡\theta_{\min}, so C∗=C(θmin⁡)C^* = C(\theta_{\min}). The refit of line L14 changes the returned model but not C∗C^*. □\square

Remark (why the stopping rule is a heuristic for MSAC). In RANSAC, the inlier ratio of line L12 never exceeds the ratio of the best model, so the rule never stops early under its assumptions. In MSAC, the model of least cost so far can have more inliers than θmin⁡\theta_{\min}. Example: with T=1T = 1, a model with 6 inliers at residual 0.9 each and 4 outliers costs 6(0.81)+4=8.866(0.81) + 4 = 8.86, and a model with 5 inliers at residual 0 and 5 outliers costs 55. The first has more inliers and a higher cost. If the first is the best so far, the rule uses w=0.6w = 0.6 instead of 0.50.5 and can stop before the count that θmin⁡\theta_{\min} needs. So for MSAC, the count of line L12 is a heuristic, not a bound.

Remark (ties). The test of line L9 is strict, so among models of equal cost the first one found is kept. In the example of the page, the lines y=0.1y = 0.1 and y=0y = 0 have the same inliers but costs 0.155 and 0.145, so MSAC keeps y=0y = 0 even though it is found second, while RANSAC keeps y=0.1y = 0.1.

Complexity

One round costs the minimal solver, O(1)O(1) for a fixed model type, plus nn residuals and a sum, so Θ(n)\Theta(n) in the real RAM, the same as a round of RANSAC. With kk rounds the time is Θ(kn)\Theta(k n), and the extra space is Θ(n)\Theta(n) for the squared residuals and the inlier set. The number of rounds kk is random and at most kmax⁡k_{\max}. When the best model has inlier ratio ww, the rule of line L12 asks for about log⁡(1−p)/log⁡(1−ws)\log(1 - p)/\log(1 - w^s) rounds, as in the iteration bound.

Properties

  • Same loop as RANSAC. Only the score differs. The cost per round is the same up to a constant.
  • Bounded influence. An outlier adds T2T^2 however large its residual is, so a far outlier cannot move the result (the cost is redescending, the same as the inlier count).
  • Finer ranking. Models with the same inliers are ranked by how well they fit them, so ties of RANSAC are broken in favor of the better fit (a theorem about the score, shown in the example). Torr and Zisserman report that this gives more accurate models at no extra cost (a benchmark result of their paper).
  • Less sensitive to TT. For a fixed model, the cost is a continuous function of TT, while the inlier count jumps by whole items. An item that crosses the threshold changes the cost by almost nothing.

Variants and improvements

  • MLESAC replaces the truncated quadratic with the negative log-likelihood of a mixture of Gaussian inliers and uniform outliers, and estimates the mixing weight for each model.
  • MAGSAC removes the fixed threshold: it marginalizes the cost over a range of noise scales.
  • LO-RANSAC with the truncated quadratic cost in its local step (LO+ of Lebeda, Matas and Chum, 2012) combines MSAC scoring with local optimization.
  • Other M-estimator costs. A Huber cost is not bounded, so a far outlier still pulls the result; robust samplers use bounded costs such as the truncated quadratic.
  • Least median of squares scores a model by the median squared residual, which needs no threshold but fails beyond half outliers.

When to use it

Use MSAC in place of plain RANSAC in almost every case: it costs the same per round, needs the same threshold and breaks the ties of the inlier count by the quality of fit. Use it when the result is the input to a refinement that minimizes a squared error, because the two costs agree inside the band. If the noise level is not known well, consider MAGSAC. If the score of each model must be cheap to compare early, as in preemptive RANSAC, any additive cost works, the truncated quadratic included.

Pitfalls

  • The stopping rule uses inliers. The best model by cost does not always have the most inliers. Compute the inlier ratio of line L12 from the best model by cost, and do not mix the two scores.
  • Units of TT. The cost is in squared residual units. Use the same residual in the cost, the inlier set and the refit, for example the Sampson distance for the fundamental matrix.
  • Comparing costs across data sets. The cost depends on nn and on TT. Compare costs only for the same data and threshold.
  • No refit. As in RANSAC, the model of the minimal sample is noisy. Refit on the inlier set.

Implementations

The Python code fits a line in the plane with s=2s = 2. The loop takes the minimal solver, the residual and the refit as arguments. The function msac_cost gives the truncated quadratic cost of any model, which the tests use to check 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.

msac.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/msac/. The authors are listed in prov/S7R7BT.jsonl.
"""MSAC (M-estimator sample consensus), Torr and Zisserman 2000.

The RANSAC loop with a different score: a model costs
C(theta) = sum_i min(r_i^2, T^2), a truncated quadratic, and the model of least
cost wins. Inliers still pay their squared residual, so among models with the
same number of inliers the one that fits them more tightly 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. Standard library only. Cost: O(k (C + n)) for k trials, n data items
and a solver of cost C.
"""

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 they coincide."""
    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 msac_cost(model, data, threshold, residual=point_line_distance):
    """The truncated quadratic cost sum_i min(r_i^2, T^2)."""
    t2 = threshold * threshold
    return sum(min(residual(model, x) ** 2, t2) for x in data)


def msac(data, threshold, rng=None, s=2, p=0.99, max_trials=10000,
         fit_minimal=line_through, residual=point_line_distance, refit=fit_line_lsq):
    """Return (model, inliers, cost, trials).

    cost is the truncated quadratic cost of the best sampled model, inliers
    the sorted indices with residual at most threshold for that model, and
    model the least squares refit on those inliers (or the sampled model if
    the refit fails). Returns (None, [], 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, [], math.inf, 0
    t2 = threshold * threshold
    best, best_cost, best_inl, k, t = None, math.inf, [], 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
        r2 = [residual(theta, x) ** 2 for x in data]  # @line L7
        cost = sum(min(e, t2) for e in r2)  # @line L8
        if cost < best_cost:  # @line L9
            best, best_cost = theta, cost  # @line L10
            best_inl = [i for i in range(n) if r2[i] <= t2]  # @line L11
            k = min(max_trials, ransac_trials(p, len(best_inl) / n, s))  # @line L12
    if best is None:  # @line L13
        return None, [], math.inf, t
    model = refit([data[i] for i in best_inl]) if refit is not None else None  # @line L14
    return (model if model is not None else best), best_inl, best_cost, t  # @line L15
test_msac.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/msac/. The authors are listed in prov/S7R7BT.jsonl.

import itertools
import math
import random

from msac import fit_line_lsq, line_through, msac, msac_cost, point_line_distance, ransac_trials

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


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 test_example_costs():
    y0 = line_through([(0, 0), (4, 0)])
    y01 = line_through([(1, 0.1), (3, 0.1)])
    assert abs(msac_cost(y0, EXAMPLE, 0.25) - 0.145) < 1e-12
    assert abs(msac_cost(y01, EXAMPLE, 0.25) - 0.155) < 1e-12
    # both lines have the same 5 inliers, so RANSAC cannot tell them apart
    for line in (y0, y01):
        assert [i for i, x in enumerate(EXAMPLE) if point_line_distance(line, x) <= 0.25] == [0, 1, 2, 3, 4]
    assert ransac_trials(0.99, 5 / 7, 2) == 7


def test_example_run():
    model, inl, cost, _ = msac(EXAMPLE, 0.25, random.Random(1))
    assert inl == [0, 1, 2, 3, 4]
    assert abs(cost - 0.145) < 1e-12
    assert abs(model[0]) < 1e-12 and abs(model[1] - 1.0) < 1e-12 and abs(model[2] + 0.04) < 1e-12
    best = min(msac_cost(line_through(pq), EXAMPLE, 0.25)
               for pq in itertools.combinations(EXAMPLE, 2) if line_through(pq) is not None)
    assert abs(cost - best) < 1e-12


def test_cost_is_least_among_sampled_models():
    for seed in range(4):
        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(msac_cost(line, data, 0.15))
            return line

        _, _, cost, t = msac(data, 0.15, random.Random(50 + seed), fit_minimal=solver)
        assert len(seen) == t
        assert cost == min(seen)


def test_outliers_are_truncated():
    line = line_through([(0, 0), (1, 0)])
    near = [(0, 0), (1, 0), (2, 5)]
    far = [(0, 0), (1, 0), (2, 500)]
    assert msac_cost(line, near, 0.5) == msac_cost(line, far, 0.5) == 0.25


def test_planted_line():
    data, true_line = planted(random.Random(3), 50, 50, sigma=0.05, gap=0.5)
    model, inl, _, _ = msac(data, 0.15, random.Random(5))
    assert all(i < 50 for i in inl) and len(inl) >= 49
    assert line_angle(model, true_line) < math.radians(1.0)


def test_exact_data():
    data, true_line = planted(random.Random(7), 40, 60)
    model, inl, cost, _ = msac(data, 0.05, random.Random(2))
    assert inl == list(range(40))
    assert abs(cost - 60 * 0.05 ** 2) < 1e-9
    assert line_angle(model, true_line) < 1e-9


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

History

Torr and Zisserman published MSAC in 2000, in their paper on MLESAC in Computer Vision and Image Understanding. They observed that RANSAC minimizes a cost that is 0 for an inlier and 1 for an outlier, so it is an M-estimator with a step function, and that a truncated quadratic gives a better estimate at the same cost. The idea comes from the M-estimators of robust statistics, which Huber introduced in 1964. In the USAC framework of Raguram, Chum, Pollefeys, Matas and Frahm (2013), the truncated quadratic score is a standard part, and later methods such as MAGSAC take it as the base cost to improve on.

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 section that compares the RANSAC cost with the truncated quadratic cost of MSAC, before the definition of MLESAC
  2. 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
  3. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 4.7, Robust estimation (the distance threshold from the chi-square distribution)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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