Algorithm Search⌘K

Algorithmresearch

Fast global registration

Also called FGR.

Aligns point clouds from feature matches by minimizing a Geman-McClure robust cost with a line process and a shrinking scale, with no closest point queries.

Time
Θ(N m) worst · average · best
Space
Θ(m) extra
Where
N = the number of iterations; m = the number of correspondences
Properties
deterministicnot exactofflineiterative
Origin
Qian Yi Zhou, Jaesik Park, Vladlen Koltun, 2016

Fast global registration (FGR) aligns two point clouds from a fixed set of correspondences, found once by matching local feature descriptors such as FPFH. Many of the matches can be wrong. FGR minimizes a robust cost, the scaled Geman-McClure function of the match residuals, which grows like a square for small residuals and tends to a constant μ\mu for large ones, so a wrong match has a bounded effect. It writes this cost with a line process: a weight per match, chosen in closed form, turns the cost into a weighted least squares problem in the pose. Each iteration sets the weights, takes one Gauss-Newton step on the six parameters of a small rigid motion, and every few iterations makes μ\mu smaller, so the cost moves from nearly least squares to strongly robust. Unlike iterative closest point, FGR never searches for closest points during the optimization, which makes each iteration cheap, and it needs no start pose.

In plain words

You have a list of guessed matches between two scans, made once from the shape around each point. Some guesses are wrong.

Give each match a weight. Find the turn and shift that best fit the matches, counting each by its weight. A match that the current pose fits badly gets a small weight, so it pulls less in the next round. Repeat.

At first, the method is tolerant: even a badly fit match keeps much of its weight, so all matches pull together and the scans swing into rough place. Then, step by step, it becomes strict: a match must fit closely to keep its weight. The wrong matches fade out, and the right ones fix the pose.

The method never asks which point is closest to which. It only works with the list it was given.

The problem

Input. Correspondences (pk,qk)(p_k, q_k) with pk,qk∈R3p_k, q_k \in \mathbb{R}^3, for k=1,…,mk = 1, \ldots, m; a start value μ0\mu_0 of the scale; and a final value δ2\delta^2.

Output. A rigid motion T=(R,t)T = (R, t), with R∈SO(3)R \in SO(3), at a stationary point of

E(T)=∑k=1mρ(∣qk−Tpk∣),ρ(x)=μx2μ+x2,E(T) = \sum_{k=1}^{m} \rho(|q_k - T p_k|), \qquad \rho(x) = \frac{\mu x^2}{\mu + x^2},

reached through the sequence of decreasing μ\mu. The cost ρ\rho is a redescending M-estimator: its influence goes to zero for large residuals. FGR does not promise the global minimum. This is point cloud registration with given correspondences, a form of robust model fitting.

The algorithm

The line process. FGR minimizes the joint cost

E(T,L)=∑klk∣qk−Tpk∣2+∑kμ(lk−1)2E(T, L) = \sum_{k} l_k |q_k - T p_k|^2 + \sum_k \mu (\sqrt{l_k} - 1)^2

over the pose and the weights lk≥0l_k \ge 0. For a fixed pose, the best weight of a match with residual rr is l=(μ/(μ+r2))2l = (\mu / (\mu + r^2))^2, and putting it in gives back ρ(r)\rho(r). For fixed weights, the cost is a weighted least squares cost in TT.

The pose step. Write a small motion as ξ=(ω,v)\xi = (\omega, v): the rotation by the vector ω\omega, then the shift vv. For xk=Tpkx_k = T p_k, the residual after the motion is about rk+Jkξr_k + J_k \xi, with rk=xk−qkr_k = x_k - q_k and Jk=[−[xk]×∣I]J_k = [-[x_k]_\times \mid I]. Minimizing ∑klk∣rk+Jkξ∣2\sum_k l_k |r_k + J_k \xi|^2 gives the 6×66 \times 6 normal equations Hξ=−gH \xi = -g.

  1. FGR(P, Q, μ₀, δ) ▷ correspondences (p_k, q_k), k = 1 .. m
  2. 1R ← I ; t ← 0 ; μ ← μ₀
  3. 2for it = 1 .. N
  4. 3l_k ← (μ / (μ + |T p_k - q_k|²))² for each k
  5. 4H ← Σ_k l_k J_kᵀ J_k ; g ← Σ_k l_k J_kᵀ (T p_k - q_k)
  6. 5ξ ← -H⁻¹ g
  7. 6T ← exp(ξ) T
  8. 7if it is a multiple of 4: μ ← max(μ / 2, δ²)
  9. 8return T

Line L1 starts at the identity. The paper sets μ0=D2\mu_0 = D^2, where DD is the diameter of the largest surface; the reference code uses the diagonal of the box around both sets. Line L3 is the closed-form weight of the line process. Lines L4 and L5 are the Gauss-Newton step of weighted least squares with these weights. Line L6 applies the motion: the rotation by ω\omega, as in Rodrigues' formula, then the shift. Line L7 is the graduated non-convexity schedule: the paper halves μ\mu every four iterations until it reaches δ2\delta^2, for a small distance threshold δ\delta set by the user. Some implementations, such as Open3D, divide by 1.4 instead of 2.

The correspondences. FGR finds them once, before line L1. For each point it computes a descriptor such as FPFH and finds the nearest descriptor in the other cloud, in both directions. The reciprocity test keeps a pair only if each point is the other's nearest, as in mutual nearest neighbor matching. The tuple test then picks random triples of pairs and keeps the pairs of a triple when all three distances in one cloud agree with the matching distances in the other within a factor τ\tau, with τ=0.9\tau = 0.9: τ<∣pi−pj∣/∣qi−qj∣<1/τ\tau < |p_i - p_j| / |q_i - q_j| < 1 / \tau. A rigid motion keeps distances, so right matches pass this test.

Example

Take eight points p1,…,p8p_1, \ldots, p_8: (0,0,0)(0, 0, 0), (1,0,0)(1, 0, 0), (0,2,0)(0, 2, 0), (0,0,3)(0, 0, 3), (1,1,0)(1, 1, 0), (2,0,1)(2, 0, 1), (0,1,2)(0, 1, 2), (1,2,3)(1, 2, 3). The true motion turns by 90 degrees about the zz axis and shifts by (1,0,0)(1, 0, 0). Six matches are right; the matches of p3p_3 and p6p_6 are wrong, with q3=(3,3,3)q_3 = (3, 3, 3) and q6=(−2,1,0)q_6 = (-2, 1, 0). The box around both sets has the diagonal D2=43D^2 = 43, so μ0=43\mu_0 = 43, and δ2\delta^2 is small. The table shows the state after each listed iteration: the μ\mu of that iteration, the angle between the estimate and the true rotation, the translation, the weights of the two wrong matches, and the cost EE at that μ\mu.

iteration μ\mu rotation error tt l3l_3 l6l_6 EE
1 43 83.51° (-0.009, 0.411, -0.163) 0.481 0.497 31.608
4 43 84.10° (0.060, 0.564, -0.120) 0.516 0.516 31.390
8 21.5 8.49° (0.766, -0.045, -0.050) 0.174 0.361 20.798
12 10.75 18.85° (1.023, 0.063, 0.018) 0.053 0.335 13.236
16 5.375 7.37° (1.001, 0.016, 0.004) 0.018 0.130 8.187
20 2.688 2.27° (0.999, 0.004, 0.001) 0.005 0.041 4.643
24 1.344 0.67° (0.999, 0.001, 0.000) 0.001 0.012 2.489
32 0.336 0.049° (1.000, 0.000, 0.000) 0.000 0.001 0.659
40 0.084 0.003° (1.000, 0.000, 0.000) 0.000 0.000 0.167

With μ=43\mu = 43, every match keeps about half its weight or more, and the fit is close to least squares over all eight matches: the rotation is still far off. When μ\mu falls to 21.5, the pose swings to within 8.5 degrees. At μ=10.75\mu = 10.75 the error grows again to about 19 degrees while EE falls: the wrong match q6q_6 still has weight 0.34 and pulls the pose toward it. As μ\mu falls further, the two wrong matches lose their weight, and the six right ones fix the pose. After 64 iterations the rotation error is below 10−510^{-5} degrees and t=(1,0,0)t = (1, 0, 0) to eight digits. Within each stage of fixed μ\mu, EE falls at every step in this run.

Correctness

The proof in proofs/correctness.md shows three facts. First, the line process is exact: l=(μ/(μ+r2))2l = (\mu / (\mu + r^2))^2 is the unique best weight, and the joint cost with this weight equals ρ(r)\rho(r). Second, the vector gg of line L4 is half the gradient of EE with respect to a small motion, because ρ′\rho' as a function of r2r^2 is exactly the weight ll. Third, if the points TpkT p_k do not all lie on one line, HH is positive definite, so the step ξ=−H−1g\xi = -H^{-1} g is zero exactly at a stationary point of EE, and otherwise it is a descent direction: a short enough step along ξ\xi lowers EE. This is the standard link between iteratively reweighted least squares and robust costs.

The claims are weaker than they may seem. FGR takes the full step, and a full Gauss-Newton step is not proved to lower EE; a line search would make each stage monotone. Each change of μ\mu changes the cost. A stationary point need not be the global minimum, and graduated non-convexity is a heuristic, not a guarantee. The method is called global because it needs no start pose, not because it proves global optimality.

Proof: The line process gives the Geman-McClure cost, and the FGR step is a descent directionfull

We use the notation of the page. There are mm correspondences (pk,qk)(p_k, q_k) in R3\mathbb{R}^3, the current pose is T=(R,t)T = (R, t), xk=Tpk=Rpk+tx_k = T p_k = R p_k + t and rk=xk−qkr_k = x_k - q_k. For μ>0\mu > 0 the cost is

E(T)=∑k=1mρ(∣rk∣2),ρ(s)=μsμ+s,E(T) = \sum_{k=1}^{m} \rho(|r_k|^2), \qquad \rho(s) = \frac{\mu s}{\mu + s},

where we write ρ\rho as a function of the squared residual s=∣r∣2s = |r|^2. A small motion ξ=(ω,v)∈R6\xi = (\omega, v) \in \mathbb{R}^6 moves the pose to TξT_\xi, with Tξp=exp⁡(ω)(Rp+t)+vT_\xi p = \exp(\omega)(R p + t) + v, where exp⁡(ω)\exp(\omega) is the rotation by the vector ω\omega. We prove three facts. They show that each step of FGR is a correct line process step and a descent direction. They do not show that the full step lowers EE, and they do not show that FGR finds the global minimum.

Lemma 1: the line process

For s≥0s \ge 0 and μ>0\mu > 0, the function h(l)=ls+μ(l−1)2h(l) = l s + \mu (\sqrt l - 1)^2 on l≥0l \ge 0 has the unique minimizer l⋆=(μ/(μ+s))2l^\star = (\mu / (\mu + s))^2, and h(l⋆)=ρ(s)h(l^\star) = \rho(s).

Proof. Put u=l≥0u = \sqrt l \ge 0. Then h=u2s+μ(u−1)2h = u^2 s + \mu (u - 1)^2, a strictly convex quadratic in uu because its leading coefficient s+μs + \mu is positive. Its derivative 2us+2μ(u−1)2 u s + 2 \mu (u - 1) is zero at u⋆=μ/(μ+s)u^\star = \mu / (\mu + s), which lies in (0,1](0, 1], so it is the minimizer over u≥0u \ge 0, and l⋆=(u⋆)2l^\star = (u^\star)^2. With 1−u⋆=s/(μ+s)1 - u^\star = s / (\mu + s),

h(l⋆)=μ2s(μ+s)2+μs2(μ+s)2=μs(μ+s)(μ+s)2=ρ(s).□h(l^\star) = \frac{\mu^2 s}{(\mu + s)^2} + \frac{\mu s^2}{(\mu + s)^2} = \frac{\mu s (\mu + s)}{(\mu + s)^2} = \rho(s). \qquad \square

So min⁡LE(T,L)=E(T)\min_L E(T, L) = E(T) for the joint cost E(T,L)=∑klk∣rk∣2+∑kμ(lk−1)2E(T, L) = \sum_k l_k |r_k|^2 + \sum_k \mu(\sqrt{l_k} - 1)^2, and line L3 computes the minimizing LL for the current TT.

Lemma 2: the gradient

Let Jk=[−[xk]×∣I]J_k = [-[x_k]_\times \mid I], so that Jkξ=ω×xk+vJ_k \xi = \omega \times x_k + v, and let g=∑klkJkTrkg = \sum_k l_k J_k^{\mathsf T} r_k with lk=l⋆(∣rk∣2)l_k = l^\star(|r_k|^2). Then ddεE(Tεξ)∣ε=0=2gTξ\frac{d}{d\varepsilon} E(T_{\varepsilon \xi}) \big|_{\varepsilon = 0} = 2 g^{\mathsf T} \xi for every ξ\xi.

Proof. The rotation by εω\varepsilon \omega is I+ε[ω]×+O(ε2)I + \varepsilon [\omega]_\times + O(\varepsilon^2), so Tεξpk=xk+ε(ω×xk+v)+O(ε2)T_{\varepsilon \xi} p_k = x_k + \varepsilon(\omega \times x_k + v) + O(\varepsilon^2), and the derivative of rkr_k along ε\varepsilon is JkξJ_k \xi. The derivative of ρ\rho is ρ′(s)=μ2/(μ+s)2=l⋆(s)\rho'(s) = \mu^2 / (\mu + s)^2 = l^\star(s). By the chain rule, the derivative of ρ(∣rk∣2)\rho(|r_k|^2) is lk⋅2rkTJkξl_k \cdot 2 r_k^{\mathsf T} J_k \xi. Summing over kk gives 2gTξ2 g^{\mathsf T} \xi. □\square

Lemma 3: the matrix of the step

Let H=∑klkJkTJkH = \sum_k l_k J_k^{\mathsf T} J_k. Then HH is positive semidefinite, and it is positive definite if and only if the points x1,…,xmx_1, \ldots, x_m do not all lie on one line.

Proof. ξTHξ=∑klk∣ω×xk+v∣2≥0\xi^{\mathsf T} H \xi = \sum_k l_k |\omega \times x_k + v|^2 \ge 0, and every lk>0l_k > 0 because l⋆(s)>0l^\star(s) > 0 for finite ss. So ξTHξ=0\xi^{\mathsf T} H \xi = 0 exactly when ω×xk+v=0\omega \times x_k + v = 0 for all kk. If ω=0\omega = 0, this forces v=0v = 0. If ω≠0\omega \ne 0, the solutions xx of ω×x=−v\omega \times x = -v form a line parallel to ω\omega or the empty set. So a nonzero ξ\xi with ξTHξ=0\xi^{\mathsf T} H \xi = 0 exists if and only if all xkx_k lie on one line. □\square

Theorem

Assume that the points xkx_k do not all lie on one line. Then the step ξ=−H−1g\xi = -H^{-1} g of line L5:

  1. minimizes the linearized cost ∑klk∣rk+Jkξ∣2\sum_k l_k |r_k + J_k \xi|^2 of the joint cost with LL fixed;
  2. is zero if and only if TT is a stationary point of EE (in the sense that every directional derivative of Lemma 2 is zero);
  3. is a descent direction when it is not zero: there is ε0>0\varepsilon_0 > 0 such that E(Tεξ)<E(T)E(T_{\varepsilon \xi}) < E(T) for all 0<ε<ε00 < \varepsilon < \varepsilon_0.

Proof. (1) The linearized cost is ∑klk∣rk∣2+2gTξ+ξTHξ\sum_k l_k |r_k|^2 + 2 g^{\mathsf T} \xi + \xi^{\mathsf T} H \xi, a strictly convex quadratic by Lemma 3; its minimizer solves Hξ=−gH \xi = -g. (2) HH is invertible, so ξ=0\xi = 0 if and only if g=0g = 0, and by Lemma 2 g=0g = 0 if and only if every directional derivative is zero. (3) By Lemma 2 the derivative of E(Tεξ)E(T_{\varepsilon \xi}) at ε=0\varepsilon = 0 is 2gTξ=−2gTH−1g2 g^{\mathsf T} \xi = -2 g^{\mathsf T} H^{-1} g, which is negative when g≠0g \ne 0, because H−1H^{-1} is positive definite. A function with a negative derivative at 0 is below its value at 0 on a small interval (0,ε0)(0, \varepsilon_0). □\square

What this does not prove

  • FGR takes the full step ε=1\varepsilon = 1. For this step, the theorem gives no decrease. A line search on ε\varepsilon would give a monotone method at a fixed μ\mu; the paper and the reference code do not use one. In tests the full step decreased EE at a fixed μ\mu, but this is not a proof.
  • Each change of μ\mu changes the cost, so EE values at different μ\mu are not comparable.
  • A stationary point of EE need not be the global minimum. The large first μ\mu makes the first cost close to least squares, which is easy to minimize, and the later costs are reached gradually; this is the idea of graduated non-convexity, and it helps in practice, but it is not a guarantee.

Complexity

The model is the real RAM. Lines L3 and L4 take Θ(m)\Theta(m) time per iteration, and line L5 solves a 6×66 \times 6 system in O(1)O(1). So NN iterations take Θ(Nm)\Theta(N m) time and Θ(m)\Theta(m) extra space. The reference code uses a fixed number of iterations, 64 by default, so the cost of the optimization is small.

The correspondences cost more. For nn points per cloud, the descriptors take time that depends on the descriptor; FPFH with kk neighbors takes O(nk)O(n k) after a neighbor search. The nearest neighbor search in descriptor space takes Θ(n2)\Theta(n^2) by brute force, as in the reference code, or less with a k-d tree or an approximate search. The tuple test takes O(1)O(1) per triple.

Properties

  • No closest point queries. The correspondences are fixed. ICP searches for closest points in every iteration; FGR does not.
  • No start pose. FGR starts at the identity, and the large first μ\mu lets distant matches pull the clouds into place.
  • Robust. The Geman-McClure cost bounds the cost of a wrong match by μ\mu, and its weight tends to 0. In tests, the reference code recovers the pose with 70% of the matches wrong.
  • Not certified. FGR gives no proof that its result is the global minimum, unlike TEASER.
  • Deterministic. The optimization is deterministic. The tuple test uses random triples.
  • Depends on the features. If the descriptors give too few right matches, no robust cost can recover the pose.

Variants and improvements

  • Multi-way registration. The paper also aligns many scans at once, with one line process per pair of scans and a joint step over all poses.
  • The schedule. Open3D divides μ\mu by 1.4 and stops when μ\mu is small. Other robust costs, such as the Tukey biweight or truncated least squares, fit into the same scheme.
  • Graduated non-convexity in general. Yang, Antonante, Tzoumas and Carlone (2020) give the same idea for many robust costs and many problems, and TEASER++ uses it for the rotation.
  • Refinement. A few iterations of ICP after FGR refine the pose on all points.

When to use it

Use FGR for global registration of two scans when good local features are available and a fast answer matters, such as in the reconstruction of indoor scenes from many scans. It is usually faster than RANSAC on the same matches, because it needs no sampling and no repeated tests of hypotheses. When the fraction of wrong matches is very high, use TEASER, which is built for that case and can certify its result. When the clouds are already close, use ICP. When no features are available, use Go-ICP or 4-points congruent sets.

Pitfalls

  • Units. μ\mu and δ\delta are squared lengths. If the clouds are in millimeters and δ\delta was set for meters, the final cost is far too strict or too tolerant. Normalize the clouds or set δ\delta from the noise level.
  • Stopping too early. If μ\mu stays large, the wrong matches keep their weight and bias the pose, as in iteration 12 of the example.
  • Degenerate geometry. If the points of the matches lie near one line, HH is singular or badly conditioned, and the step is not defined.
  • Rotation updates. Apply the step as a rotation, not as I+[ω]×I + [\omega]_\times, or the estimate drifts away from a rotation matrix.
  • Too many tuples. The tuple test keeps a pair if any of its triples passes. With many random triples, a wrong pair often finds one that passes by chance, so the test removes fewer wrong pairs.
  • Symmetric scenes. If the scene has a symmetry, the matches can support a wrong pose as well as the right one.

Implementations

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.

cvgeom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Camera geometry and synthetic scenes for the computer vision pages.

Conventions (prompts of the area, also stated on the pages):
- The camera frame has X to the right, Y down and Z forward. A point is in
  front of the camera if Z > 0.
- K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]] in pixels.
- A world point Xw maps to the camera frame by Xc = R Xw + t. The camera
  matrix is P = K [R | t], and the center is C = -R^T t.
- Rotations are active and right-handed. Quaternions are (w, x, y, z) in the
  Hamilton convention.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import math
import random
from typing import Dict, List, Optional, Sequence, Tuple

from cvla import det, matvec, mul, solve, transpose

Matrix = List[List[float]]
Vector = List[float]


def to_h(x: Sequence[float]) -> Vector:
    """Append a 1: the homogeneous vector of a point."""
    return [float(v) for v in x] + [1.0]


def from_h(x: Sequence[float]) -> Vector:
    """Divide by the last entry and drop it. Raises ValueError if the last
    entry is zero (a point at infinity)."""
    w = x[-1]
    if w == 0:
        raise ValueError("from_h: point at infinity")
    return [v / w for v in x[:-1]]


def make_K(fx: float, fy: float, cx: float, cy: float, s: float = 0.0) -> Matrix:
    """The intrinsic matrix [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
    return [[float(fx), float(s), float(cx)],
            [0.0, float(fy), float(cy)],
            [0.0, 0.0, 1.0]]


def camera_matrix(K: Sequence[Sequence[float]], R: Sequence[Sequence[float]],
                  t: Sequence[float]) -> Matrix:
    """The 3 x 4 camera matrix P = K [R | t]."""
    rt = [list(R[i]) + [t[i]] for i in range(3)]
    return mul(K, rt)


def project(P: Sequence[Sequence[float]], X):
    """Pixel coordinates (u, v) of a point X under the camera P.

    X is a 3D point (3 entries) or a homogeneous point (4 entries). If X is
    a list of points, the result is the list of their projections."""
    if len(X) > 0 and isinstance(X[0], (list, tuple)):
        return [project(P, x) for x in X]
    xh = to_h(X) if len(X) == 3 else list(X)
    return from_h(matvec(P, xh))


def camera_center(P: Sequence[Sequence[float]]) -> Vector:
    """The center C of a finite camera P = [M | p4]: C = -M^-1 p4, so that
    P (C, 1) = 0."""
    m = [list(row[:3]) for row in P]
    p4 = [row[3] for row in P]
    return [-v for v in solve(m, p4)]


def rot_x(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the X axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def axis_angle_to_R(axis: Sequence[float], theta: Optional[float] = None) -> Matrix:
    """Rotation by theta (radians) about the axis, by the right-hand rule
    (Rodrigues formula). The axis need not be a unit vector. If theta is
    None, axis is the rotation vector w = theta a, with theta = ||w||."""
    n = math.sqrt(sum(float(v) * float(v) for v in axis))
    if theta is None:
        theta = n
    if n == 0.0 or theta == 0.0:
        return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    x, y, z = (float(v) / n for v in axis)
    c, s = math.cos(theta), math.sin(theta)
    d = 1.0 - c
    return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
            [y * x * d + z * s, c + y * y * d, y * z * d - x * s],
            [z * x * d - y * s, z * y * d + x * s, c + z * z * d]]


def quat_to_R(q: Sequence[float]) -> Matrix:
    """Rotation matrix of the quaternion q = (w, x, y, z), Hamilton
    convention. q is normalized first; q and -q give the same matrix."""
    n = math.sqrt(sum(float(v) * float(v) for v in q))
    if n == 0.0:
        raise ValueError("quat_to_R: zero quaternion")
    w, x, y, z = (float(v) / n for v in q)
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def random_rotation(rng: random.Random) -> Matrix:
    """A rotation drawn from the uniform (Haar) distribution: a uniform
    random unit quaternion by the method of Shoemake (1992)."""
    u1, u2, u3 = rng.random(), rng.random(), rng.random()
    a, b = math.sqrt(1.0 - u1), math.sqrt(u1)
    q = (b * math.cos(2 * math.pi * u3), a * math.sin(2 * math.pi * u2),
         a * math.cos(2 * math.pi * u2), b * math.sin(2 * math.pi * u3))
    return quat_to_R(q)


def _small_rotation(rng: random.Random, max_angle: float) -> Matrix:
    axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
    return axis_angle_to_R(axis, rng.uniform(0.0, max_angle))


def random_scene(rng: random.Random, n: int = 20, n_cams: int = 2,
                 K: Optional[Sequence[Sequence[float]]] = None,
                 cams: Optional[Sequence[Tuple]] = None,
                 radius: float = 1.0, distance: float = 5.0,
                 max_angle: float = 0.3, planar: bool = False,
                 first_identity: bool = False,
                 size: Optional[Tuple[float, float]] = None,
                 min_depth: float = 0.1) -> Dict[str, list]:
    """A synthetic scene with known cameras and points.

    Cameras: if cams is given, it is a list of (K, R, t) and is used as it
    is. Otherwise n_cams cameras look at the world origin from the distance
    `distance`. Each one is the camera at center (0, 0, -distance) with
    R = I, turned about the origin by a random rotation of angle at most
    max_angle (radians). K defaults to make_K(800, 800, 320, 240). With
    first_identity, the world frame is moved to the frame of camera 0, so
    that camera 0 has R = I and t = 0 (the points move with it).

    Points: n points drawn uniformly in the cube [-radius, radius]^3 (with
    Z = 0 if planar, before any move of the world frame). A point is kept
    only if its depth is at least min_depth in every camera, and, if size =
    (W, H) is given, if its projection lies in [0, W] x [0, H] in every
    camera. Raises ValueError if 1000 n draws are not enough.

    Returns a dict with lists "K", "R", "t", "P" (one entry per camera),
    "X" (the 3D points) and "x" (x[i][j] is the pixel of point j in
    camera i, without noise)."""
    if cams is not None:
        Ks = [[list(r) for r in c[0]] for c in cams]
        Rs = [[list(r) for r in c[1]] for c in cams]
        ts = [list(c[2]) for c in cams]
    else:
        k0 = [list(r) for r in K] if K is not None else make_K(800, 800, 320, 240)
        Ks, Rs, ts = [], [], []
        c0 = [0.0, 0.0, -float(distance)]
        for _ in range(n_cams):
            q = _small_rotation(rng, max_angle)
            r = transpose(q)
            center = matvec(q, c0)
            Ks.append([list(row) for row in k0])
            Rs.append(r)
            ts.append([-v for v in matvec(r, center)])
    pts: List[Vector] = []
    tries = 0
    while len(pts) < n:
        tries += 1
        if tries > 1000 * max(n, 1):
            raise ValueError("random_scene: cannot place the points")
        x = [rng.uniform(-radius, radius) for _ in range(3)]
        if planar:
            x[2] = 0.0
        ok = True
        for k, r, t in zip(Ks, Rs, ts):
            xc = [a + b for a, b in zip(matvec(r, x), t)]
            if xc[2] < min_depth:
                ok = False
                break
            if size is not None:
                u = (k[0][0] * xc[0] + k[0][1] * xc[1]) / xc[2] + k[0][2]
                v = k[1][1] * xc[1] / xc[2] + k[1][2]
                if not (0.0 <= u <= size[0] and 0.0 <= v <= size[1]):
                    ok = False
                    break
        if ok:
            pts.append(x)
    if first_identity and Rs:
        r0, t0 = Rs[0], ts[0]
        pts = [[a + b for a, b in zip(matvec(r0, x), t0)] for x in pts]
        r0t = transpose(r0)
        newR, newt = [], []
        for r, t in zip(Rs, ts):
            rr = mul(r, r0t)
            newR.append(rr)
            newt.append([a - b for a, b in zip(t, matvec(rr, t0))])
        Rs, ts = newR, newt
        Rs[0] = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
        ts[0] = [0.0, 0.0, 0.0]
    Ps = [camera_matrix(k, r, t) for k, r, t in zip(Ks, Rs, ts)]
    xs = [[project(p, x) for x in pts] for p in Ps]
    return {"K": Ks, "R": Rs, "t": ts, "P": Ps, "X": pts, "x": xs}


def add_noise(rng: random.Random, pts: Sequence[Sequence[float]], sigma: float) -> List[Vector]:
    """A copy of the points with independent Gaussian noise of standard
    deviation sigma added to every coordinate."""
    return [[float(v) + rng.gauss(0.0, sigma) for v in p] for p in pts]


def self_test() -> None:
    """Check random_scene and quat_to_R. Raises AssertionError."""
    rng = random.Random(11)
    scene = random_scene(rng, n=30, n_cams=4)
    for r, t in zip(scene["R"], scene["t"]):
        for x in scene["X"]:
            assert matvec(r, x)[2] + t[2] > 0.0
    for _ in range(5):
        q = [rng.gauss(0.0, 1.0) for _ in range(4)]
        r = quat_to_R(q)
        rtr = mul(transpose(r), r)
        assert all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) <= 1e-12
                   for i in range(3) for j in range(3))
        assert abs(det(r) - 1.0) <= 1e-12


if __name__ == "__main__":
    self_test()
cvla.py 494 lines
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import cmath
import math
from typing import List, Sequence, Tuple

Matrix = List[List[float]]
Vector = List[float]

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


# ---------------------------------------------------------------- basics

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """The cross product a x b of two 3-vectors."""
    return [a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0]]


def skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


# ---------------------------------------------------------- polynomials

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
fast_global_registration.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-global-registration/. The authors are listed in prov/MFA6WR.jsonl.
"""Fast global registration (Zhou, Park and Koltun, ECCV 2016).

Input: correspondences (p_k, q_k) in R^3, k = 1 .. m, from feature
matching. Most of them can be wrong. Output: a rigid motion T = (R, t) that
minimizes the scaled Geman-McClure cost

    E(T) = sum_k rho(|q_k - T p_k|),   rho(x) = mu x^2 / (mu + x^2).

FGR writes E with a line process: E(T, L) = sum_k l_k |q_k - T p_k|^2 +
sum_k mu (sqrt(l_k) - 1)^2. For a fixed T the best l_k is
(mu / (mu + r_k^2))^2, and minimizing over l_k gives back rho. For a fixed L
the cost is a weighted least squares cost in T, which FGR reduces by one
Gauss-Newton step on the six parameters xi = (omega, v) of a small motion
exp(xi) T. The value mu starts large, so the cost is close to least squares,
and falls every few iterations (graduated non-convexity).

The correspondences come from the features by mutual nearest neighbors
(the reciprocity test) and a tuple test on random triples.
"""

from __future__ import annotations

import math
import random
from typing import Dict, List, Optional, Sequence, Tuple

from cvgeom import axis_angle_to_R
from cvla import matvec, mul, solve

Vector = List[float]
Matrix = List[List[float]]


def _apply(R: Matrix, t: Vector, p: Sequence[float]) -> Vector:
    Rp = matvec(R, p)
    return [Rp[0] + t[0], Rp[1] + t[1], Rp[2] + t[2]]


def _dist2(a: Sequence[float], b: Sequence[float]) -> float:
    return sum((x - y) * (x - y) for x, y in zip(a, b))


def geman_mcclure(r2: float, mu: float) -> float:
    """rho(r) = mu r^2 / (mu + r^2), given r^2."""
    return mu * r2 / (mu + r2)


def line_process_weight(r2: float, mu: float) -> float:
    """The best l for a residual r: (mu / (mu + r^2))^2."""
    return (mu / (mu + r2)) ** 2


def fgr_cost(P, Q, R: Matrix, t: Vector, mu: float) -> float:
    """E(T) = sum_k rho(|q_k - T p_k|)."""
    return sum(geman_mcclure(_dist2(q, _apply(R, t, p)), mu) for p, q in zip(P, Q))


def _nearest(f: Sequence[float], F: Sequence[Sequence[float]]) -> int:
    best, bi = math.inf, -1
    for i, g in enumerate(F):
        d = _dist2(f, g)
        if d < best:
            best, bi = d, i
    return bi


def match_features(P, Q, FP, FQ, tau: float = 0.9, n_tuples: int = 1000,
                   rng: Optional[random.Random] = None) -> List[Tuple[int, int]]:
    """Correspondences from features, by the reciprocity test and the tuple
    test. FP[i] is the feature of P[i] and FQ[j] the feature of Q[j]. Brute
    force nearest neighbors in feature space, O(|P| |Q|) distances."""
    rng = rng or random.Random(0)
    fwd = [_nearest(f, FQ) for f in FP]
    bwd = [_nearest(g, FP) for g in FQ]
    mutual = [(i, j) for i, j in enumerate(fwd) if bwd[j] == i]
    if len(mutual) < 3:
        return mutual
    keep = set()
    for _ in range(n_tuples):
        trio = rng.sample(mutual, 3)
        ok = True
        for a in range(3):
            for b in range(a + 1, 3):
                dp = math.sqrt(_dist2(P[trio[a][0]], P[trio[b][0]]))
                dq = math.sqrt(_dist2(Q[trio[a][1]], Q[trio[b][1]]))
                if dp == 0.0 or dq == 0.0 or not (tau < dp / dq < 1.0 / tau):
                    ok = False
        if ok:
            keep.update(trio)
    return sorted(keep)


def gauss_newton_step(P, Q, R: Matrix, t: Vector, mu: float):
    """One step at the pose T = (R, t). Returns (xi, l, H, g): the weights
    l_k of the line process, the 6 x 6 matrix H = sum_k l_k J_k^T J_k, the
    vector g = sum_k l_k J_k^T r_k, and the step xi = -H^-1 g. Here
    r_k = T p_k - q_k, and J_k = [-[x_k]_x | I] with x_k = T p_k is the
    derivative of exp(xi) T p_k at xi = 0. g is half the gradient of E.
    Raises ValueError if H is singular."""
    Tp = [_apply(R, t, p) for p in P]
    lw = [line_process_weight(_dist2(q, x), mu) for x, q in zip(Tp, Q)]  # @line L3
    H = [[0.0] * 6 for _ in range(6)]
    g = [0.0] * 6
    for x, q, l in zip(Tp, Q, lw):  # @line L4
        r = [x[0] - q[0], x[1] - q[1], x[2] - q[2]]
        J = [[0.0, x[2], -x[1], 1.0, 0.0, 0.0],
             [-x[2], 0.0, x[0], 0.0, 1.0, 0.0],
             [x[1], -x[0], 0.0, 0.0, 0.0, 1.0]]
        for c in range(3):
            Jc = J[c]
            for a in range(6):
                if Jc[a] == 0.0:
                    continue
                g[a] += l * Jc[a] * r[c]
                for b in range(6):
                    H[a][b] += l * Jc[a] * Jc[b]
    xi = solve(H, [-v for v in g])  # @line L5
    return xi, lw, H, g


def compose(xi: Sequence[float], R: Matrix, t: Vector) -> Tuple[Matrix, Vector]:
    """The pose after the small motion xi = (omega, v): x -> dR (R x + t) + v,
    where dR is the rotation by the vector omega."""
    dR = axis_angle_to_R(xi[:3])
    return mul(dR, R), [a + b for a, b in zip(matvec(dR, t), xi[3:])]


def fgr(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]],
        mu0: Optional[float] = None, delta: float = 0.01, factor: float = 2.0,
        every: int = 4, max_iter: int = 64) -> Dict[str, object]:
    """Align p_k to q_k. mu starts at mu0 (default: D^2, with D the diameter
    of the box around both sets) and is divided by factor every `every`
    iterations, but not below delta^2. Returns R, t, the final mu, the
    weights l and the history of the cost E (at the mu of each step)."""
    m = len(P)
    if m == 0:
        raise ValueError("fgr: no correspondences")
    if mu0 is None:
        pts = list(P) + list(Q)
        D2 = sum((max(p[d] for p in pts) - min(p[d] for p in pts)) ** 2 for d in range(3))
        mu0 = max(D2, delta * delta)
    R: Matrix = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]  # @line L1
    t: Vector = [0.0, 0.0, 0.0]
    mu = mu0
    history: List[float] = []
    lw: List[float] = [1.0] * m
    for it in range(max_iter):  # @line L2
        try:
            xi, lw, _, _ = gauss_newton_step(P, Q, R, t, mu)
        except ValueError:
            break
        R, t = compose(xi, R, t)  # @line L6
        history.append(fgr_cost(P, Q, R, t, mu))
        if (it + 1) % every == 0 and mu > delta * delta:  # @line L7
            mu = max(mu / factor, delta * delta)
    return {"R": R, "t": t, "mu": mu, "l": lw, "history": history}  # @line L8
test_fast_global_registration.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-global-registration/. The authors are listed in prov/MFA6WR.jsonl.
import math
import random
import unittest

from cvgeom import axis_angle_to_R, random_rotation
from cvla import mul, transpose
from fast_global_registration import (compose, fgr, fgr_cost, gauss_newton_step,
                                      geman_mcclure, line_process_weight, match_features)


def rot_angle(R1, R2):
    m = mul(transpose(R1), R2)
    c = max(-1.0, min(1.0, (m[0][0] + m[1][1] + m[2][2] - 1.0) / 2.0))
    return math.acos(c)


def make_problem(rng, m, n_out, noise, R=None):
    R = R or random_rotation(rng)
    t = [rng.uniform(-1.0, 1.0) for _ in range(3)]
    P = [[rng.uniform(-1.0, 1.0) for _ in range(3)] for _ in range(m)]
    Q = [[sum(R[i][k] * p[k] for k in range(3)) + t[i] + rng.gauss(0.0, noise) for i in range(3)] for p in P]
    for k in rng.sample(range(m), n_out):
        Q[k] = [rng.uniform(-2.0, 2.0) for _ in range(3)]
    return R, t, P, Q


class TestLineProcess(unittest.TestCase):
    def test_weight_minimizes_and_gives_rho(self):
        for mu in [0.01, 1.0, 25.0]:
            for r2 in [0.0, 0.003, 0.5, 4.0, 100.0]:
                l = line_process_weight(r2, mu)
                best = min(L * r2 + mu * (math.sqrt(L) - 1.0) ** 2 for L in (g / 20000.0 for g in range(20001)))
                val = l * r2 + mu * (math.sqrt(l) - 1.0) ** 2
                self.assertLessEqual(val, best + 1e-9)
                self.assertAlmostEqual(val, geman_mcclure(r2, mu), places=12)

    def test_rho_is_bounded(self):
        self.assertAlmostEqual(geman_mcclure(1e12, 2.0), 2.0, places=9)
        self.assertEqual(geman_mcclure(0.0, 2.0), 0.0)


class TestStep(unittest.TestCase):
    def test_g_is_half_the_gradient(self):
        rng = random.Random(1)
        _, _, P, Q = make_problem(rng, 15, 5, 0.01)
        R, t, mu = axis_angle_to_R([0.2, -0.1, 0.3]), [0.1, 0.0, -0.2], 0.5
        _, _, _, g = gauss_newton_step(P, Q, R, t, mu)
        h = 1e-6
        for a in range(6):
            e = [0.0] * 6
            e[a] = h
            Rp, tp = compose(e, R, t)
            e[a] = -h
            Rm, tm = compose(e, R, t)
            fd = (fgr_cost(P, Q, Rp, tp, mu) - fgr_cost(P, Q, Rm, tm, mu)) / (2 * h)
            self.assertAlmostEqual(fd, 2.0 * g[a], places=5)

    def test_step_is_a_descent_direction(self):
        rng = random.Random(2)
        for _ in range(10):
            _, _, P, Q = make_problem(rng, 20, 8, 0.01)
            R, t = random_rotation(rng), [rng.uniform(-1, 1) for _ in range(3)]
            mu = rng.choice([0.1, 1.0, 10.0])
            xi, _, _, g = gauss_newton_step(P, Q, R, t, mu)
            self.assertLess(sum(a * b for a, b in zip(xi, g)), 0.0)
            e0 = fgr_cost(P, Q, R, t, mu)
            R1, t1 = compose([1e-4 * v for v in xi], R, t)
            self.assertLess(fgr_cost(P, Q, R1, t1, mu), e0)


class TestFGR(unittest.TestCase):
    def test_exact_data_large_rotation(self):
        rng = random.Random(3)
        R = axis_angle_to_R([1.0, 2.0, -1.0], math.radians(150.0))
        R, t, P, Q = make_problem(rng, 30, 0, 0.0, R)
        out = fgr(P, Q, delta=1e-4, max_iter=120)
        self.assertLess(rot_angle(R, out["R"]), 1e-6)
        for a, b in zip(out["t"], t):
            self.assertAlmostEqual(a, b, places=6)

    def test_many_outliers(self):
        for seed in (4, 5):
            rng = random.Random(seed)
            R, t, P, Q = make_problem(rng, 60, 42, 0.005)
            out = fgr(P, Q)
            self.assertLess(rot_angle(R, out["R"]), math.radians(1.0))
            for a, b in zip(out["t"], t):
                self.assertLess(abs(a - b), 0.02)

    def test_weights_separate_inliers(self):
        rng = random.Random(6)
        R, t, P, Q = make_problem(rng, 40, 0, 0.002)
        bad = rng.sample(range(40), 12)
        for k in bad:
            Q[k] = [rng.uniform(-2.0, 2.0) for _ in range(3)]
        out = fgr(P, Q)
        for k, l in enumerate(out["l"]):
            if k in bad:
                self.assertLess(l, 0.1)
            else:
                self.assertGreater(l, 0.9)


class TestMatching(unittest.TestCase):
    def test_reciprocity_and_tuples(self):
        rng = random.Random(7)
        R, t, P, Q = make_problem(rng, 40, 0, 0.0)
        FP = [[rng.uniform(0.0, 10.0) for _ in range(4)] for _ in range(40)]
        FQ = [[f + rng.gauss(0.0, 0.01) for f in fp] for fp in FP]
        swap = rng.sample(range(40), 10)
        for a, b in zip(swap[::2], swap[1::2]):  # five pairs of points trade features
            FQ[a], FQ[b] = FQ[b], FQ[a]
        # All 40 pairs pass the reciprocity test, 10 of them wrong. With few
        # tuples, the tuple test keeps every right pair and drops most wrong ones.
        pairs = match_features(P, Q, FP, FQ, n_tuples=2000, tau=1e-9, rng=random.Random(8))
        self.assertEqual(len(pairs), 40)
        pairs = match_features(P, Q, FP, FQ, n_tuples=200, rng=random.Random(8))
        good = [(i, j) for i, j in pairs if i == j]
        self.assertEqual(len(good), 30)
        self.assertLessEqual(len(pairs) - len(good), 5)


if __name__ == "__main__":
    unittest.main()

History

Zhou, Park and Koltun presented FGR at ECCV 2016. The method combines three older ideas: the line process of Black and Rangarajan (1996), which links robust costs and weighted least squares; graduated non-convexity, from the work of Blake and Zisserman on visual reconstruction; and the matching of local 3D features such as the FPFH descriptor of Rusu, Blodow and Beetz (2009). FGR became part of the Open3D library, where it is a common first step before ICP.

References

  1. Qian-Yi Zhou, Jaesik Park and Vladlen Koltun, Fast global registration, Computer Vision, ECCV 2016, Lecture Notes in Computer Science 9906, Springer, 2016, 766-782, The scaled Geman-McClure cost, the line process and its closed-form weights, the linearized update of the pose, the schedule of the scale mu, and the reciprocity and tuple tests for the correspondences
  2. Paul J. Besl and Neil D. McKay, A method for registration of 3-D shapes, IEEE Transactions on Pattern Analysis and Machine Intelligence 14(2), 1992, 239-256, The ICP algorithm, the local method with closest point queries that FGR avoids

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
  • at least three sources
  • a scene preset for the example