Algorithm Search⌘K

Algorithmresearch

MAGSAC

Also called marginalizing sample consensus, MAGSAC++.

RANSAC with no inlier threshold, scoring and refining each model by marginalizing a robust cost over a range of noise scales.

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
Daniel Barath, Jiri Matas, Jana Noskova, Maksym Ivashechkin, 2019

MAGSAC (marginalizing sample consensus) is a variant of RANSAC that needs no inlier threshold. RANSAC and MSAC need a threshold TT that separates inliers from outliers, and the result can change a lot with TT. MAGSAC asks only for an upper bound σmax⁡\sigma_{\max} on the noise scale. It treats the unknown scale σ\sigma as uniform on [0,σmax⁡][0, \sigma_{\max}] and averages, or marginalizes, the inlier density over it. This gives a smooth weight w(r)w(r) for each residual rr and a bounded loss ρ(r)=∫0rx w(x) dx\rho(r) = \int_0^r x\,w(x)\,dx. A model is scored by the sum of the losses, and each new best model is refined by a weighted least squares fit with the weights ww. Barath, Matas and Noskova published MAGSAC in 2019. MAGSAC++ (Barath, Noskova, Ivashechkin and Matas, 2020) gave the loss in closed form and wrote the refinement as iteratively reweighted least squares. This page describes MAGSAC++.

In plain words

Plain RANSAC needs a fixed distance limit: points closer than the limit count as good, points farther count as bad. If the limit is too tight, good points are lost. If it is too loose, bad points get in. The right limit depends on the noise, which is often not known.

MAGSAC does not choose one limit. It tries all limits up to a maximum and averages the results. A point that is close to the guess counts as good for almost every limit, so it gets a large weight. A point that is a little farther counts as good only for the loose limits, so it gets a smaller weight. A point beyond the largest limit gets no weight. The guess with the smallest total penalty wins, and the weights then pull it to a better fit.

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)≥0r(\theta, x) \ge 0 with ν\nu degrees of freedom, a noise bound σmax⁡\sigma_{\max}, a confidence pp and a cap kmax⁡k_{\max}. The model of the noise is: for an inlier, r/σr/\sigma follows a chi distribution with ν\nu degrees of freedom, cut at a quantile kk. The goal is a model of small quality

Q(θ)=∑i=1nρ(r(θ,xi)).Q(\theta) = \sum_{i=1}^{n} \rho\big(r(\theta, x_i)\big).

This is an M-estimator form of robust model fitting with a bounded loss. The code fits a 2D affine map q=Ap+bq = A p + b from s=3s = 3 point pairs, with r=∥Ap+b−q∥r = \lVert A p + b - q \rVert and ν=2\nu = 2. For ν=2\nu = 2 the weight is

w(r)=1σmax⁡π2(erfc⁡(r2 σmax⁡)−erfc⁡(k2)) for r<kσmax⁡,w(r)=0 after.w(r) = \frac{1}{\sigma_{\max}} \sqrt{\frac{\pi}{2}} \Big(\operatorname{erfc}\big(\tfrac{r}{\sqrt{2}\,\sigma_{\max}}\big) - \operatorname{erfc}\big(\tfrac{k}{\sqrt{2}}\big)\Big) \text{ for } r < k\sigma_{\max}, \qquad w(r) = 0 \text{ after}.

For other ν\nu, the papers write ww and ρ\rho with incomplete gamma functions. For ν=2\nu = 2 they reduce to erf⁡\operatorname{erf} and erfc⁡\operatorname{erfc}.

The algorithm

  1. MAGSAC++(D, σ_max, p, k_max) ▷ n = |D|, s items per sample
  2. 1θ* ← none, Q* ← ∞, k ← k_max, t ← 0
  3. 2while t < k do
  4. 3t ← t + 1
  5. 4θ ← FIT-MINIMAL(s distinct items of D, drawn uniformly at random)
  6. 5if θ is none then continue ▷ degenerate sample
  7. 6Q ← Σ_i ρ(r(θ, x_i))
  8. 7if Q < Q* then
  9. 8θ' ← SIGMA-CONSENSUS++(θ)
  10. 9if Q(θ') < Q then θ ← θ', Q ← Q(θ')
  11. 10θ* ← θ, Q* ← Q
  12. 11k ← min(k_max, stopping count of θ* averaged over noise scales)
  13. 12return θ*, Q*
  14. SIGMA-CONSENSUS++(θ)
  15. 13repeat a fixed number of times
  16. 14w_i ← w(r(θ, x_i)) for i = 1, …, n
  17. 15θ ← argmin over θ of Σ_i w_i r(θ, x_i)²
  18. 16return θ

Lines L6 and L7 replace the inlier count of RANSAC with the marginalized loss. Lines L13 to L15 are iteratively reweighted least squares: items with a small residual get a large weight, and items beyond kσmax⁡k\sigma_{\max} get weight 0. Line L11 of the code takes the scales σj=j σmax⁡/d\sigma_j = j\,\sigma_{\max}/d for j=1,…,dj = 1, \ldots, d, counts the items with r≤kσjr \le k\sigma_j, applies the RANSAC formula ⌈log⁡(1−p)/log⁡(1−wjs)⌉\lceil \log(1-p)/\log(1-w_j^s) \rceil to each ratio wjw_j, caps each count at kmax⁡k_{\max} and takes the mean. MAGSAC also defines a stopping rule that takes the unknown noise scale into account. The rule of the code is a simple version of this idea, not the formula of the papers.

Example

Take σmax⁡=0.5\sigma_{\max} = 0.5 and the 7 point pairs (0,0)→(1,0.1)(0,0) \to (1, 0.1), (1,0)→(2,0)(1,0) \to (2,0), (0,1)→(1,1)(0,1) \to (1,1), (1,1)→(2.1,1)(1,1) \to (2.1, 1) and (2,1)→(3,1)(2,1) \to (3,1), which follow a shift by (1,0)(1, 0) with small errors, and the outliers (2,2)→(5,−1)(2,2) \to (5,-1) and (0,2)→(−2,4)(0,2) \to (-2,4). The code uses k=−2ln⁡0.01≈3.035k = \sqrt{-2 \ln 0.01} \approx 3.035, the 0.99 quantile of the chi distribution with 2 degrees of freedom, so items with r≥kσmax⁡≈1.517r \ge k\sigma_{\max} \approx 1.517 get weight 0 and the largest loss, ρmax⁡≈0.3050\rho_{\max} \approx 0.3050.

sample residuals of the 7 pairs QQ
pairs 1, 2, 3 0, 0, 0, 0.141, 0.2, 3.36, 3.66 0.0213+0.0395+2(0.3050)=0.67080.0213 + 0.0395 + 2(0.3050) = 0.6708
pairs 1, 5, 6 0, 1.85, 3.52, 1.71, 0, 0, 10.6 1.2199
pairs 1, 2, 4 0, 0, 0.141, 0, 0.141, 3.41, 3.72 0.6525

A sample with an outlier puts the other inliers far from the model, so it pays ρmax⁡\rho_{\max} many times. The two outliers cost the same ρmax⁡\rho_{\max} for every good model, however far they are. Now polish the first model. Its weights are 2.502.50 for the three exact pairs, 1.941.94 and 1.721.72 for the next two and 0 for the outliers. One weighted fit lowers QQ to 0.62270.6227, and after the second step Q=0.62259Q = 0.62259 with A=(10.032−0.0200.96)A = \begin{pmatrix} 1 & 0.032 \\ -0.020 & 0.96 \end{pmatrix} and b=(1,0.06)b = (1, 0.06). Over all 32 samples of 3 pairs that are not collinear, the least QQ is 0.6323, so the polished model is better than every minimal model. With p=0.99p = 0.99 and d=10d = 10, line L11 gives k=11k = 11, and for the seeds 0 to 3 the run stops after 11 rounds with Q=0.62259Q = 0.62259.

Correctness

Four facts make the method sound (proofs below). First, w(r)w(r) is equal to the density of the residual of an inlier, averaged over σ\sigma uniform on [0,σmax⁡][0, \sigma_{\max}], with the density at each σ\sigma cut at kσk\sigma. Second, ww is non-negative and non-increasing, so ρ\rho is non-decreasing and constant beyond kσmax⁡k\sigma_{\max}: a far outlier adds a fixed cost and cannot pull the model. Third, the closed form of ρ\rho in the code has derivative r w(r)r\,w(r) and value 0 at 0. Fourth, one step of lines L14 and L15 never increases QQ. The function v↦ρ(v)v \mapsto \rho(\sqrt{v}) is concave, so the weighted squares give an upper bound of QQ that touches it at the current model. The loop keeps the invariant that θ∗\theta^* has the least QQ among all models it has evaluated, and it ends after at most kmax⁡k_{\max} rounds. As for RANSAC, the result is optimal only if a good sample is drawn, so the stopping rule is a heuristic.

Proof: The MAGSAC++ loss is the integral of the marginal weight, each sigma-consensus++ step does not increase it, and the loop returns the best model it has seenfull

We use the notation of the page. The residual of an item is r≥0r \ge 0, with ν=2\nu = 2 degrees of freedom, a noise bound σmax⁡>0\sigma_{\max} > 0 and a cut k>0k > 0. Write a=2 σmax⁡a = \sqrt{2}\,\sigma_{\max} and c=erfc⁡(k/2)c = \operatorname{erfc}(k/\sqrt{2}). For 0≤r<kσmax⁡0 \le r < k\sigma_{\max},

w(r)=1σmax⁡π2(erfc⁡(r/a)−c),w(r) = \frac{1}{\sigma_{\max}} \sqrt{\frac{\pi}{2}} \big(\operatorname{erfc}(r/a) - c\big),

and w(r)=0w(r) = 0 for r≥kσmax⁡r \ge k\sigma_{\max}. The loss is ρ(r)=∫0rx w(x) dx\rho(r) = \int_0^{r} x\, w(x)\, dx, and the quality of a model is Q(θ)=∑iρ(ri(θ))Q(\theta) = \sum_i \rho(r_i(\theta)), lower is better. The model of computation is the real RAM, with erf⁡\operatorname{erf}, erfc⁡\operatorname{erfc} and exp⁡\exp as unit-cost operations.

Claim. (a) For 0<r<kσmax⁡0 < r < k\sigma_{\max}, w(r)=1σmax⁡∫r/kσmax⁡rσ2e−r2/(2σ2) dσw(r) = \frac{1}{\sigma_{\max}} \int_{r/k}^{\sigma_{\max}} \frac{r}{\sigma^2} e^{-r^2/(2\sigma^2)}\, d\sigma, the density of the residual of an inlier at rr, averaged over σ\sigma uniform on [0,σmax⁡][0, \sigma_{\max}], with the density of each σ\sigma cut at kσk\sigma. (b) ww is non-negative, continuous and non-increasing on [0,∞)[0, \infty), and ρ\rho is non-decreasing, bounded and constant for r≥kσmax⁡r \ge k\sigma_{\max}. (c) The closed form of ρ\rho in the code is equal to ∫0rx w(x) dx\int_0^r x\, w(x)\, dx. (d) If θ1\theta_1 minimizes ∑iw(ri(θ0)) ri(θ)2\sum_i w(r_i(\theta_0))\, r_i(\theta)^2, then Q(θ1)≤Q(θ0)Q(\theta_1) \le Q(\theta_0). (e) The loop of lines L1 to L12 ends after at most kmax⁡k_{\max} rounds, and it returns a model whose quality is the least over all models it has evaluated, and that quality.

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

Proof. Substitute u=r/(2 σ)u = r/(\sqrt{2}\,\sigma), so σ=r/(2 u)\sigma = r/(\sqrt{2}\,u) and dσ=−r/(2 u2) dud\sigma = -r/(\sqrt{2}\,u^2)\, du. Then rσ2e−r2/(2σ2) dσ=−2u2re−u2r2 u2 du=−2 e−u2 du\frac{r}{\sigma^2} e^{-r^2/(2\sigma^2)}\, d\sigma = -\frac{2u^2}{r} e^{-u^2} \frac{r}{\sqrt{2}\,u^2}\, du = -\sqrt{2}\, e^{-u^2}\, du. The limit σ=r/k\sigma = r/k goes to u=k/2u = k/\sqrt{2}, and σ=σmax⁡\sigma = \sigma_{\max} goes to u=r/au = r/a. So the integral is 2∫r/ak/2e−u2 du=2 π2(erfc⁡(r/a)−c)\sqrt{2} \int_{r/a}^{k/\sqrt{2}} e^{-u^2}\, du = \sqrt{2}\, \frac{\sqrt{\pi}}{2} \big(\operatorname{erfc}(r/a) - c\big). Divide by σmax⁡\sigma_{\max} to get w(r)w(r). The integrand is the chi density with 2 degrees of freedom of rr at scale σ\sigma, and r<kσr < k\sigma is the same as σ>r/k\sigma > r/k. □\square

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

Proof. The function erfc⁡\operatorname{erfc} is continuous and strictly decreasing. For r<kσmax⁡r < k\sigma_{\max}, r/a<k/2r/a < k/\sqrt{2}, so erfc⁡(r/a)>c\operatorname{erfc}(r/a) > c and w(r)>0w(r) > 0. At r=kσmax⁡r = k\sigma_{\max} the bracket is 0, so ww is continuous there, and it is 0 after. So ww is non-negative, continuous and non-increasing. Then x w(x)≥0x\, w(x) \ge 0, so ρ\rho is non-decreasing, and x w(x)=0x\, w(x) = 0 for x≥kσmax⁡x \ge k\sigma_{\max}, so ρ\rho is constant there. The constant is finite, because it is the integral of a continuous function on a bounded interval. □\square

Lemma 3 (closed form). Part (c) holds.

Proof. Let e(r)=e−r2/a2e(r) = e^{-r^2/a^2} and let R(r)=12r2erfc⁡(r/a)+14a2erf⁡(r/a)−ar e(r)2π−12r2cR(r) = \frac{1}{2} r^2 \operatorname{erfc}(r/a) + \frac{1}{4} a^2 \operatorname{erf}(r/a) - \frac{a r\, e(r)}{2\sqrt{\pi}} - \frac{1}{2} r^2 c, so the code computes ρ(r)=1σmax⁡π2 R(min⁡(r,kσmax⁡))\rho(r) = \frac{1}{\sigma_{\max}}\sqrt{\frac{\pi}{2}}\, R(\min(r, k\sigma_{\max})). Use ddrerfc⁡(r/a)=−2aπe(r)\frac{d}{dr}\operatorname{erfc}(r/a) = -\frac{2}{a\sqrt{\pi}} e(r) and e′(r)=−2ra2e(r)e'(r) = -\frac{2r}{a^2} e(r). The four terms of RR have the derivatives rerfc⁡(r/a)−r2eaπr \operatorname{erfc}(r/a) - \frac{r^2 e}{a\sqrt{\pi}}, ae2π\frac{a e}{2\sqrt{\pi}}, −ae2π+r2eaπ-\frac{a e}{2\sqrt{\pi}} + \frac{r^2 e}{a\sqrt{\pi}} and −rc-r c. Their sum is r(erfc⁡(r/a)−c)r\big(\operatorname{erfc}(r/a) - c\big). So ddrρ(r)=r w(r)\frac{d}{dr}\rho(r) = r\, w(r) for r<kσmax⁡r < k\sigma_{\max}. Also R(0)=0R(0) = 0. By the fundamental theorem of calculus, the code gives ∫0rx w(x) dx\int_0^r x\, w(x)\, dx for r≤kσmax⁡r \le k\sigma_{\max}. For larger rr the code uses R(kσmax⁡)R(k\sigma_{\max}), which is correct by Lemma 2. □\square

Lemma 4 (one reweighting step does not increase the loss). Part (d) holds.

Proof. Let φ(v)=ρ(v)\varphi(v) = \rho(\sqrt{v}) for v≥0v \ge 0. For v>0v > 0, φ′(v)=ρ′(v)/(2v)=w(v)/2\varphi'(v) = \rho'(\sqrt{v}) / (2\sqrt{v}) = w(\sqrt{v})/2 by Lemma 3. By Lemma 2 this derivative is non-increasing in vv, and φ\varphi is continuous at 0, so φ\varphi is concave on [0,∞)[0, \infty), with right derivative w(0)/2w(0)/2 at 0. A concave function lies below its tangent: φ(v)≤φ(v0)+12w(v0)(v−v0)\varphi(v) \le \varphi(v_0) + \frac{1}{2} w(\sqrt{v_0})(v - v_0) for all v,v0≥0v, v_0 \ge 0. Put v=ri(θ)2v = r_i(\theta)^2, v0=ri(θ0)2v_0 = r_i(\theta_0)^2 and wi=w(ri(θ0))w_i = w(r_i(\theta_0)), and add over ii:

Q(θ)≤Q(θ0)+12(∑iwi ri(θ)2−∑iwi ri(θ0)2).Q(\theta) \le Q(\theta_0) + \frac{1}{2}\Big(\sum_i w_i\, r_i(\theta)^2 - \sum_i w_i\, r_i(\theta_0)^2\Big).

The right side is equal to Q(θ0)Q(\theta_0) at θ=θ0\theta = \theta_0. Since θ1\theta_1 minimizes ∑iwi ri(θ)2\sum_i w_i\, r_i(\theta)^2, the bracket is at most 0 at θ=θ1\theta = \theta_1, so Q(θ1)≤Q(θ0)Q(\theta_1) \le Q(\theta_0). □\square

Lemma 4 is the step of a majorize-minimize method: the weighted squares give an upper bound of QQ that touches it at the current model. For the affine map, ri(θ)2r_i(\theta)^2 is a quadratic in the 6 parameters, and line L15 solves the weighted normal equations exactly when their matrix is regular. So every pass of lines L13 to L15 that returns a model does not increase QQ. The code keeps the old model when the matrix is singular.

Lemma 5 (loop). Part (e) holds.

Proof. Each round raises tt by 1 at line L3, and line L11 never sets the bound above kmax⁡k_{\max}, so the loop of line L2 ends after at most kmax⁡k_{\max} rounds. For the invariant, we show that at each test of line L2, Q∗Q^* is the least quality over all models evaluated so far (the minimal models of line L6 and the polished models of line L9), and θ∗\theta^* has the quality Q∗Q^*. At the start no model has been evaluated and Q∗=∞Q^* = \infty. In a round, line L6 evaluates θ\theta. If Q(θ)≥Q∗Q(\theta) \ge Q^*, nothing else is evaluated and the invariant holds. Otherwise line L8 makes a polished model θ′\theta', line L9 evaluates it and keeps the better of θ\theta and θ′\theta', and line L10 stores it. Its quality is less than the old Q∗Q^*, and it is the least of the two new values, so the invariant holds again. At the end, line L12 returns θ∗\theta^* and Q∗Q^*. □\square

Remark (what is not proved). As in RANSAC, the loop finds a model of least quality only if one of the samples it draws leads to it. The stopping rule of line L11 is a heuristic: it uses the inlier ratio of the best model at a set of noise scales. The papers report the accuracy of MAGSAC and MAGSAC++ in experiments, and these results are not theorems.

Complexity

One round costs the minimal solver, O(1)O(1) for a fixed model type, plus nn residuals and losses, so Θ(n)\Theta(n) in the real RAM, with erf⁡\operatorname{erf} and exp⁡\exp at unit cost. A new best model also costs a fixed number of weighted fits of O(n)O(n) each, and the stopping count costs O(d n)O(d\,n). With a fixed number of reweighting steps and a fixed dd, kk rounds cost Θ(kn)\Theta(k n), the same order as RANSAC. A round has a larger constant than in RANSAC, because the loss uses erfc⁡\operatorname{erfc} and exp⁡\exp. The extra space is Θ(n)\Theta(n) for the residuals and weights.

Properties

  • No hard threshold. Only σmax⁡\sigma_{\max} is needed. Changing σmax⁡\sigma_{\max} changes the loss smoothly. The papers report better accuracy than threshold-based methods on homography and epipolar geometry benchmarks (an experimental result).
  • Bounded loss. ρ\rho is constant beyond kσmax⁡k\sigma_{\max}, as the truncated quadratic of MSAC is beyond TT.
  • Monotone refinement. Each reweighting step does not increase QQ, a majorize-minimize argument.
  • Randomized. Like RANSAC, the result depends on the samples drawn.

Variants and improvements

  • MAGSAC (2019) approximates the marginalization over σ\sigma by fits at a finite set of noise scales. MAGSAC++ replaces it with the closed-form loss and the reweighted least squares step, which is faster.
  • Progressive NAPSAC. The MAGSAC++ paper also proposes a sampler that first draws samples from small neighborhoods and then from larger ones.
  • MSAC and MLESAC are the threshold-based scores that MAGSAC generalizes.
  • LO-RANSAC refines each new best model too, but with a fixed threshold.
  • PROSAC changes the sampling order and can be combined with the MAGSAC++ score.

When to use it

Use MAGSAC++ when the noise level is not known well enough to choose a threshold, for example when the same pipeline runs on images of different sizes or quality. It fits the same problems as RANSAC: homographies, fundamental matrices and essential matrices. If a good threshold is known and speed matters most, MSAC with LO-RANSAC is simpler.

Pitfalls

  • The degrees of freedom. The weight depends on ν\nu, the dimension of the residual. Use the ν\nu that matches the residual, for example 2 for a point-to-point error in the image and 1 for a point-to-line error.
  • The scale of σmax⁡\sigma_{\max}. σmax⁡\sigma_{\max} is an upper bound, not the noise level. A value that is far too large lets outliers get weight.
  • Degenerate weighted fits. If fewer than ss items have non-zero weight, the weighted normal equations are singular. Keep the old model in that case.
  • Numerics of erfc. For large arguments, compute erfc⁡\operatorname{erfc} directly, not as 1−erf⁡1 - \operatorname{erf}, to keep small weights accurate.

Implementations

The Python code fits a 2D affine map with s=3s = 3 and ν=2\nu = 2. The functions magsac_weight and magsac_loss give the closed forms of ww and ρ\rho, and sigma_consensus_pp is the reweighting loop of lines L13 to L16. The weighted fit solves two 3×33 \times 3 normal equations by Gaussian elimination. The tests check ww against a numerical integral over σ\sigma, ρ\rho against a numerical integral of x w(x)x\,w(x), the descent of each reweighting step and the example.

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.

magsac.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/magsac/. The authors are listed in prov/RA0N0V.jsonl.
"""MAGSAC++, Barath, Noskova, Ivashechkin and Matas 2020 (after MAGSAC, Barath,
Matas and Noskova 2019), for a 2D affine map q = A p + b from 3 correspondences.

No inlier threshold is fixed. The noise scale sigma is taken as uniform on
[0, sigma_max], and the residual r = |A p + b - q| of an inlier, divided by
sigma, follows a chi distribution with n = 2 degrees of freedom, truncated at
k sigma. Marginalizing the inlier density over sigma gives a weight w(r) and a
loss rho(r) = integral_0^r x w(x) dx. A model scores sum_i rho(r_i), lower is
better. Each new best model is polished by iteratively reweighted least squares
with the weights w(r_i) (sigma-consensus++). For n = 2 every incomplete gamma
function reduces to erf and erfc, so w and rho have closed forms here.
Standard library only.
"""

import math
import random

K_CHI2_99 = math.sqrt(-2.0 * math.log(0.01))  # 0.99 quantile of chi with 2 dof, about 3.035


def magsac_weight(r, sigma_max, k=K_CHI2_99):
    """w(r) = (1/sigma_max) C(2) sqrt(2) (Gamma(1/2, r^2/2 sigma_max^2) - Gamma(1/2, k^2/2)), 0 beyond k sigma_max."""
    if r >= k * sigma_max:
        return 0.0
    a = math.sqrt(2.0) * sigma_max
    return math.sqrt(math.pi / 2.0) / sigma_max * (math.erfc(r / a) - math.erfc(k / math.sqrt(2.0)))


def magsac_loss(r, sigma_max, k=K_CHI2_99):
    """rho(r) = integral_0^r x w(x) dx, constant beyond k sigma_max."""
    r = min(r, k * sigma_max)
    a = math.sqrt(2.0) * sigma_max
    e = math.exp(-(r / a) ** 2)
    inner = (0.5 * r * r * math.erfc(r / a) + 0.25 * a * a * math.erf(r / a)
             - a * r * e / (2.0 * math.sqrt(math.pi)) - 0.5 * r * r * math.erfc(k / math.sqrt(2.0)))
    return math.sqrt(math.pi / 2.0) / sigma_max * inner


def solve3(m, v):
    """Solve a 3x3 linear system by Gaussian elimination with partial pivoting; None if singular."""
    a = [list(m[i]) + [v[i]] for i in range(3)]
    for c in range(3):
        p = max(range(c, 3), key=lambda i: abs(a[i][c]))
        if abs(a[p][c]) < 1e-12:
            return None
        a[c], a[p] = a[p], a[c]
        for i in range(c + 1, 3):
            f = a[i][c] / a[c][c]
            for j in range(c, 4):
                a[i][j] -= f * a[c][j]
    x = [0.0, 0.0, 0.0]
    for i in (2, 1, 0):
        x[i] = (a[i][3] - sum(a[i][j] * x[j] for j in range(i + 1, 3))) / a[i][i]
    return x


def fit_affine_weighted(pairs, weights):
    """argmin sum_i w_i |A p_i + b - q_i|^2 as (a11, a12, b1, a21, a22, b2), or None if degenerate."""
    m = [[0.0] * 3 for _ in range(3)]
    vx = [0.0] * 3
    vy = [0.0] * 3
    for (p, q), w in zip(pairs, weights):
        if w <= 0.0:
            continue
        row = (p[0], p[1], 1.0)
        for i in range(3):
            vx[i] += w * row[i] * q[0]
            vy[i] += w * row[i] * q[1]
            for j in range(3):
                m[i][j] += w * row[i] * row[j]
    rx = solve3(m, vx)
    ry = solve3(m, vy)
    if rx is None or ry is None:
        return None
    return (rx[0], rx[1], rx[2], ry[0], ry[1], ry[2])


def fit_affine_minimal(sample):
    """The affine map through 3 correspondences, or None if the 3 source points are collinear."""
    (p1, _), (p2, _), (p3, _) = sample
    area = (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0])
    if abs(area) < 1e-9:
        return None
    return fit_affine_weighted(sample, [1.0, 1.0, 1.0])


def residual(model, pair):
    a11, a12, b1, a21, a22, b2 = model
    (px, py), (qx, qy) = pair
    return math.hypot(a11 * px + a12 * py + b1 - qx, a21 * px + a22 * py + b2 - qy)


def total_loss(model, data, sigma_max, k=K_CHI2_99):
    return sum(magsac_loss(residual(model, x), sigma_max, k) for x in data)


def ransac_trials(p, w, s):
    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 sigma_consensus_pp(model, data, sigma_max, k=K_CHI2_99, iters=5):
    """IRLS: theta <- argmin sum_i w(r_i(theta_old)) r_i(theta)^2, a fixed number of times."""
    for _ in range(iters):  # @line L13
        w = [magsac_weight(residual(model, x), sigma_max, k) for x in data]  # @line L14
        nxt = fit_affine_weighted(data, w)  # @line L15
        if nxt is None:
            break
        model = nxt
    return model  # @line L16


def marginal_trials(model, data, sigma_max, k, p, s, max_trials, d=10):
    """The RANSAC count averaged over d noise scales sigma_j = j sigma_max / d, each capped at max_trials."""
    res = [residual(model, x) for x in data]
    n = len(data)
    total = 0.0
    for j in range(1, d + 1):
        thr = k * sigma_max * j / d
        w = sum(1 for r in res if r <= thr) / n
        total += min(max_trials, ransac_trials(p, w, s))
    return math.ceil(total / d)


def magsac_pp(data, sigma_max, rng=None, k=K_CHI2_99, p=0.99, max_trials=2000, irls_iters=5, d=10,
              on_model=None):
    """data: list of ((px, py), (qx, qy)). Return (model, loss, trials)."""
    rng = rng if rng is not None else random.Random()
    s, n = 3, len(data)
    if n < s:
        return None, math.inf, 0
    best, best_loss, kk, t = None, math.inf, max_trials, 0  # @line L1
    while t < kk:  # @line L2
        t += 1  # @line L3
        theta = fit_affine_minimal(rng.sample(data, s))  # @line L4
        if theta is None:  # @line L5
            continue
        loss = total_loss(theta, data, sigma_max, k)  # @line L6
        if on_model is not None:
            on_model(theta, loss)
        if loss < best_loss:  # @line L7
            polished = sigma_consensus_pp(theta, data, sigma_max, k, irls_iters)  # @line L8
            pl = total_loss(polished, data, sigma_max, k)
            if pl < loss:  # @line L9
                theta, loss = polished, pl
            best, best_loss = theta, loss  # @line L10
            kk = min(max_trials, marginal_trials(best, data, sigma_max, k, p, s, max_trials, d))  # @line L11
    return best, best_loss, t  # @line L12
test_magsac.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/magsac/. The authors are listed in prov/RA0N0V.jsonl.

import math
import random

from magsac import (K_CHI2_99, fit_affine_minimal, fit_affine_weighted, magsac_loss, magsac_pp,
                    magsac_weight, residual, sigma_consensus_pp, total_loss)

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


def simpson(f, a, b, m=2000):
    h = (b - a) / m
    acc = f(a) + f(b)
    for i in range(1, m):
        acc += (4 if i % 2 else 2) * f(a + i * h)
    return acc * h / 3.0


def apply(model, p):
    a11, a12, b1, a21, a22, b2 = model
    return (a11 * p[0] + a12 * p[1] + b1, a21 * p[0] + a22 * p[1] + b2)


def planted(rng, n_in, n_out, sigma):
    true = (1.1, 0.2, 2.0, -0.1, 0.9, -1.0)
    data = []
    for _ in range(n_in):
        p = (rng.uniform(0, 10), rng.uniform(0, 10))
        q = apply(true, p)
        data.append((p, (q[0] + rng.gauss(0, sigma), q[1] + rng.gauss(0, sigma))))
    for _ in range(n_out):
        p = (rng.uniform(0, 10), rng.uniform(0, 10))
        data.append((p, (rng.uniform(-5, 20), rng.uniform(-5, 20))))
    rng.shuffle(data)
    return data, true


def test_weight_is_marginal_density():
    # w(r) = (1/sigma_max) * integral over sigma in [r/k, sigma_max] of the chi(2) density r/sigma^2 exp(-r^2/2sigma^2)
    for sm in (0.5, 1.0, 2.0):
        for frac in (0.05, 0.2, 0.5, 0.9):
            r = frac * K_CHI2_99 * sm
            num = simpson(lambda s: r / (s * s) * math.exp(-r * r / (2 * s * s)) / sm, r / K_CHI2_99, sm)
            assert abs(magsac_weight(r, sm) - num) < 1e-7
        assert magsac_weight(K_CHI2_99 * sm, sm) == 0.0 and magsac_weight(10 * sm, sm) == 0.0


def test_loss_is_integral_of_x_w():
    for sm in (0.5, 1.0):
        top = K_CHI2_99 * sm
        for r in (0.1, 0.5, 1.0, 1.4, top):
            r = min(r, top)
            num = simpson(lambda x: x * magsac_weight(x, sm), 0.0, r)
            assert abs(magsac_loss(r, sm) - num) < 1e-8
        assert abs(magsac_loss(0.0, sm)) < 1e-15
        assert magsac_loss(5 * top, sm) == magsac_loss(top, sm)
    # the constant beyond k sigma_max, sigma_max C(2) sqrt(2) gamma(3/2, k^2/2)
    x = K_CHI2_99 ** 2 / 2
    g32 = 0.5 * math.sqrt(math.pi) * math.erf(math.sqrt(x)) - math.sqrt(x) * math.exp(-x)
    assert abs(magsac_loss(100.0, 1.0) - 0.5 * math.sqrt(2) * g32) < 1e-12
    assert abs(magsac_loss(100.0, 1.0) - 0.609975) < 1e-6


def test_weights_decrease_and_loss_increases():
    sm = 1.0
    rs = [i * 0.01 for i in range(400)]
    ws = [magsac_weight(r, sm) for r in rs]
    ls = [magsac_loss(r, sm) for r in rs]
    assert all(a >= b for a, b in zip(ws, ws[1:]))
    assert all(a <= b + 1e-15 for a, b in zip(ls, ls[1:]))


def test_example_values():
    sm = 0.5
    th = fit_affine_minimal(EXAMPLE[:3])
    assert all(abs(a - b) < 1e-12 for a, b in zip(th, (1.0, 0.0, 1.0, -0.1, 0.9, 0.1)))
    assert abs(total_loss(th, EXAMPLE, sm) - 0.6708) < 1e-4
    assert abs(total_loss(fit_affine_minimal([EXAMPLE[i] for i in (0, 4, 5)]), EXAMPLE, sm) - 1.2199) < 1e-4
    assert abs(total_loss(fit_affine_minimal([EXAMPLE[i] for i in (0, 1, 3)]), EXAMPLE, sm) - 0.6525) < 1e-4
    pol = sigma_consensus_pp(th, EXAMPLE, sm, iters=5)
    assert abs(total_loss(pol, EXAMPLE, sm) - 0.62259) < 1e-5
    assert all(abs(a - b) < 1e-3 for a, b in zip(pol, (1.0, 0.0322, 1.0, -0.0199, 0.96, 0.06)))
    for seed in range(4):
        model, loss, t = magsac_pp(EXAMPLE, sm, random.Random(seed))
        assert abs(loss - 0.62259) < 1e-5 and t == 11


def test_irls_never_increases_loss():
    for seed in range(5):
        rng = random.Random(seed)
        data, _ = planted(rng, 40, 30, 0.3)
        sm = 1.0
        for _ in range(10):
            th = fit_affine_minimal(rng.sample(data, 3))
            if th is None:
                continue
            prev = total_loss(th, data, sm)
            w = [magsac_weight(residual(th, x), sm) for x in data]
            if sum(1 for v in w if v > 0) < 3:
                continue
            for _ in range(6):
                nxt = sigma_consensus_pp(th, data, sm, iters=1)
                cur = total_loss(nxt, data, sm)
                assert cur <= prev + 1e-9
                th, prev = nxt, cur


def test_invariant_best_of_sampled():
    data, _ = planted(random.Random(3), 50, 50, 0.3)
    seen = []
    model, loss, t = magsac_pp(data, 1.0, random.Random(7), on_model=lambda th, q: seen.append(q))
    assert loss <= min(seen) + 1e-12
    assert abs(total_loss(model, data, 1.0) - loss) < 1e-9
    assert 1 <= t <= 2000


def test_planted_affine():
    for seed in range(3):
        data, true = planted(random.Random(20 + seed), 60, 40, 0.3)
        model, _, _ = magsac_pp(data, 1.0, random.Random(seed))
        for p in ((0, 0), (10, 0), (0, 10), (10, 10)):
            a, b = apply(model, p), apply(true, p)
            assert math.hypot(a[0] - b[0], a[1] - b[1]) < 0.5


def test_weighted_fit_exact_and_degenerate():
    true = (2.0, -1.0, 0.5, 0.3, 1.5, -2.0)
    pairs = [((x, y), apply(true, (x, y))) for x, y in ((0, 0), (1, 0), (0, 1), (2, 3), (5, 1))]
    got = fit_affine_weighted(pairs, [1.0, 2.0, 0.5, 1.0, 3.0])
    assert all(abs(a - b) < 1e-9 for a, b in zip(got, true))
    assert fit_affine_minimal([((0, 0), (0, 0)), ((1, 1), (1, 1)), ((2, 2), (3, 3))]) is None
    assert magsac_pp(EXAMPLE[:2], 0.5, random.Random(0)) == (None, math.inf, 0)

History

Barath, Matas and Noskova posted MAGSAC on arXiv in 2018 and published it at CVPR 2019. They proposed to remove the inlier threshold of RANSAC by marginalizing over the noise scale, with a new quality function and a new termination criterion. Barath, Noskova, Ivashechkin and Matas published MAGSAC++ at CVPR 2020. It derives the weight and the loss with incomplete gamma functions, writes the refinement as iteratively reweighted least squares, and adds the Progressive NAPSAC sampler. The idea of a bounded robust loss goes back to the M-estimators of robust statistics, and its use in RANSAC to MSAC and MLESAC of Torr and Zisserman (2000).

References

  1. Daniel Barath, Jiri Matas and Jana Noskova, MAGSAC: marginalizing sample consensus, IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR 2019), arXiv:1803.07469, The definition of sigma-consensus, the marginalization of the model quality over the noise scale, and the termination criterion
  2. Daniel Barath, Jana Noskova, Maksym Ivashechkin and Jiri Matas, MAGSAC++, a fast, reliable and accurate robust estimator, CVPR 2020, The MAGSAC++ quality function, its weight and loss in terms of incomplete gamma functions, and the iteratively reweighted least squares form of sigma-consensus++
  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 framework of sampling, scoring and local optimization that MAGSAC builds on

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