Algorithm Search⌘K

Algorithmcore

Iterative closest point

Also called ICP algorithm, Besl-McKay ICP.

Aligns a source point cloud to a target by repeating two steps: match each point to its closest target point, then fit the best rigid motion to the pairs. The error never rises; the result is local.

Time
Θ(N n m) worst · averageΘ(n m) best
Space
Θ(n) extra
Where
N = the number of iterations; m = the number of target points; n = the number of source points
Properties
deterministicnot exactofflineiterative
Origin
Paul J. Besl, Neil D. McKay, Yang Chen, Gérard Medioni, Zhengyou Zhang, 1992

Iterative closest point (ICP) aligns a source point cloud PP to a target point cloud QQ when no point pairs are known. It repeats two steps. First it matches each moved source point Rpi+tR p_i + t to its closest point of QQ. Then it replaces the rotation RR and the translation tt by the rigid motion that best fits the source points to their matches, which the Kabsch algorithm gives in closed form. The mean squared distance never goes up, and for finite clouds the loop stops at a fixed point after finitely many steps (the ICP convergence theorem). The result is local: from a bad start, ICP stops at a wrong pose. The Kabsch algorithm, the quaternion method and the Wahba problem solve only the fit step, with the pairs given; ICP adds the search for the pairs.

In plain words

You have two scans of the same object, taken from different places. You want to turn and slide the first scan until it lies on the second one. Nobody tells you which point goes with which.

ICP guesses. For each point of the first scan, it takes the nearest point of the second scan as its partner. With these partners fixed, there is an exact formula for the best turn and slide. Apply it, and the scans come closer. Now the nearest points may be different, so guess the partners again and repeat.

Each round makes the average squared gap smaller or keeps it the same. When the partners stop changing, ICP stops. If the first scan starts far from the right place, the nearest-point guesses are wrong in a consistent way, and ICP settles on a wrong answer.

The problem

Input. A source cloud P=(p1,…,pn)P = (p_1, \ldots, p_n) and a target cloud Q={q1,…,qm}Q = \{q_1, \ldots, q_m\} in R3\mathbb{R}^3, with n,m≥1n, m \ge 1, and a start pose (R0,t0)(R_0, t_0) with R0∈SO(3)R_0 \in SO(3). Coordinates are in meters or are unitless.

Output. A rotation R∈SO(3)R \in SO(3) (so RTR=IR^{\mathsf T} R = I and det⁡R=+1\det R = +1) and a translation t∈R3t \in \mathbb{R}^3 at a fixed point of the iteration. The goal is a small value of

E(R,t)=1n∑i=1nmin⁡j∣Rpi+t−qj∣2,E(R, t) = \frac{1}{n} \sum_{i=1}^{n} \min_{j} |R p_i + t - q_j|^2,

the mean squared closest-point distance. ICP does not promise the global minimum of EE; this is the point cloud registration problem with the closest-point cost and a local method.

The algorithm

Write c(i)c(i) for the index of the target point matched to pip_i. For a fixed match cc, the cost 1n∑i∣Rpi+t−qc(i)∣2\frac1n \sum_i |R p_i + t - q_{c(i)}|^2 is the cost of the optimal superposition problem. The Kabsch step centers both sets, forms H=∑i(pi−pˉ)(qc(i)−qˉ)TH = \sum_i (p_i - \bar p)(q_{c(i)} - \bar q)^{\mathsf T}, takes the SVD H=USVTH = U S V^{\mathsf T}, and returns R=Vdiag⁡(1,1,d) UTR = V \operatorname{diag}(1, 1, d)\, U^{\mathsf T} with d=sign⁡det⁡(VUT)d = \operatorname{sign}\det(V U^{\mathsf T}), and t=qˉ−Rpˉt = \bar q - R \bar p.

  1. ICP(P, Q, R0, t0, tol) ▷ P = (p_1 .. p_n), Q = {q_1 .. q_m}
  2. 1R ← R0 ; t ← t0 ; e_prev ← ∞ ; c_prev ← none
  3. 2repeat (up to an iteration cap)
  4. 3c(i) ← index j of the closest q_j to R p_i + t, for i = 1 .. n
  5. 4e ← (1/n) Σ_i |R p_i + t - q_c(i)|²
  6. 5if c = c_prev or e_prev - e ≤ tol then return R, t
  7. 6(R, t) ← KABSCH((p_i), (q_c(i))) ▷ R = V diag(1, 1, d) Uᵀ
  8. 7e_prev ← e ; c_prev ← c
  9. 8return R, t ▷ only when the cap ends the loop

Line L3 is the closest-point step. The reference code uses brute force and breaks ties by the lowest index; a k-d tree on QQ is the usual choice for real data (see nearest neighbor search). Line L4 is the cost at the current pose, which is the value of EE. Line L5 has two stop rules. A repeated match means that line L6 would return the same pose again. The rule eprev−e≤tole_{\text{prev}} - e \le \text{tol} stops when the cost no longer falls by more than tol; with tol =0= 0 it stops only at a fixed point. Line L6 is the alignment step. The sign dd keeps det⁡R=+1\det R = +1 when the best orthogonal matrix would be a reflection. Besl and McKay used the quaternion method of Horn for this step, which gives the same rotation.

Example

Take five source points p1=(0,0,0)p_1 = (0, 0, 0), p2=(2,0,0)p_2 = (2, 0, 0), p3=(0,1,0)p_3 = (0, 1, 0), p4=(0,0,1)p_4 = (0, 0, 1) and p5=(1,1,1)p_5 = (1, 1, 1). The target is qi=Rz(60°)pi+(0.5,0,0)q_i = R_z(60°) p_i + (0.5, 0, 0), where Rz(θ)R_z(\theta) turns by θ\theta about the zz axis. Start at R=IR = I, t=0t = 0, with tol =0= 0. The table gives the match (1-based) and the MSE after each step.

step lines match cc MSE pose after the step
1 L3, L4 (1, 1, 3, 4, 5) 0.8036 the start pose
1 L6 (1, 1, 3, 4, 5) 0.5096 a rotation of 36.04 degrees, t=(−0.0532,−0.3839,0.2871)t = (-0.0532, -0.3839, 0.2871)
2 L3, L4 (1, 2, 3, 4, 5) 0.4422 same
2 L6 (1, 2, 3, 4, 5) 0 R=Rz(60°)R = R_z(60°), t=(0.5,0,0)t = (0.5, 0, 0)
3 L3, L4, L5 (1, 2, 3, 4, 5) 0 stop: the match repeats

In step 1, p2=(2,0,0)p_2 = (2, 0, 0) is closer to q1=(0.5,0,0)q_1 = (0.5, 0, 0) than to its true partner q2=(1.5,1.732,0)q_2 = (1.5, 1.732, 0), so the first fit uses a wrong pair. The fit still lowers the MSE, and the second match is correct. The MSE values 0.8036, 0.5096, 0.4422, 0 never go up.

With the same points and other angles: 20 and 40 degrees give the exact answer after one fit (from MSE 0.2459 and 0.5076). At 90 degrees, ICP stops after one fit at MSE 0.6563, with a rotation error of 48.4 degrees. At 120 degrees it stops at MSE 0.4257 with an error of 143.0 degrees, and at 180 degrees with an error of 179.2 degrees. These are fixed points that are not the true pose: ICP is a local method.

Correctness

Claim: with tol =0= 0, ICP stops after finitely many iterations, the MSE values it meets never increase, and the returned pose has det⁡R=+1\det R = +1 and is a least squares fit to a closest-point match of itself. The key inequality is ek≥F(Rk+1,tk+1,ck)≥ek+1e_k \ge F(R_{k+1}, t_{k+1}, c_k) \ge e_{k+1}: line L6 minimizes the fixed-match cost FF, so it cannot be worse than the old pose, and the next line L3 picks the closest point for each source point, so it cannot be worse than the old match. Since the costs fall strictly until the stop, no match repeats, and there are at most mnm^n matches. The full proof is in proofs/correctness.md. The fixed point need not be a local minimum of EE when distances tie; the convergence theorem page gives an example.

Proof: ICP never increases the mean squared error and stops at a fixed pointfull

We use the notation of the page. The source is P=(p1,…,pn)P = (p_1, \ldots, p_n) and the target is Q={q1,…,qm}Q = \{q_1, \ldots, q_m\}, both in R3\mathbb{R}^3, with n,m≥1n, m \ge 1. For a rigid motion (R,t)(R, t) with R∈SO(3)R \in SO(3) and a match c:{1,…,n}→{1,…,m}c : \{1, \ldots, n\} \to \{1, \ldots, m\}, let

F(R,t,c)=1n∑i=1n∣Rpi+t−qc(i)∣2,E(R,t)=min⁡cF(R,t,c)=1n∑i=1nmin⁡j∣Rpi+t−qj∣2.F(R, t, c) = \frac{1}{n} \sum_{i=1}^{n} |R p_i + t - q_{c(i)}|^2, \qquad E(R, t) = \min_{c} F(R, t, c) = \frac{1}{n} \sum_{i=1}^{n} \min_j |R p_i + t - q_j|^2 .

Line L3 computes the closest-point match ckc_k of the pose (Rk,tk)(R_k, t_k), with ties broken by the lowest index. Line L4 computes ek=F(Rk,tk,ck)=E(Rk,tk)e_k = F(R_k, t_k, c_k) = E(R_k, t_k). Line L6 computes (Rk+1,tk+1)=FIT(ck)(R_{k+1}, t_{k+1}) = \mathrm{FIT}(c_k), the motion that the Kabsch step with the sign fix returns for the pairs (pi,qck(i))(p_i, q_{c_k(i)}). We assume exact arithmetic and the default tol =0= 0.

Claim. (a) The costs that ICP meets never increase: ek≥F(Rk+1,tk+1,ck)≥ek+1e_k \ge F(R_{k+1}, t_{k+1}, c_k) \ge e_{k+1} for every kk. (b) With tol =0= 0 and no iteration cap, ICP stops after at most mn+2m^n + 2 executions of line L3. (c) When it stops at line L5, the returned pose (R,t)(R, t) has a closest-point match cc such that (R,t)(R, t) minimizes F(⋅,⋅,c)F(\cdot, \cdot, c) over SO(3)×R3SO(3) \times \mathbb{R}^3. So (R,t)(R, t) is a fixed point of the two steps.

Lemma 1 (the fit step). For a fixed match cc, FIT(c)\mathrm{FIT}(c) minimizes F(R,t,c)F(R, t, c) over R∈SO(3)R \in SO(3) and t∈R3t \in \mathbb{R}^3.

Proof. With cc fixed, F(⋅,⋅,c)F(\cdot, \cdot, c) is 1/n1/n times the cost of the optimal superposition problem for the pairs (pi,qc(i))(p_i, q_{c(i)}). The Kabsch algorithm with the sign fix R=Vdiag⁡(1,1,d)UTR = V \operatorname{diag}(1, 1, d) U^{\mathsf T}, d=sign⁡det⁡(VUT)d = \operatorname{sign}\det(V U^{\mathsf T}), returns a global minimizer of that cost over proper rotations and translations (Umeyama 1991, and the proof on the Kabsch page). □\square

Lemma 2 (the match step). For a fixed pose (R,t)(R, t) and every match cc, E(R,t)≤F(R,t,c)E(R, t) \le F(R, t, c), with equality when cc is a closest-point match.

Proof. Each term of FF is at least min⁡j∣Rpi+t−qj∣2\min_j |R p_i + t - q_j|^2, and a closest-point match attains this minimum in every term. □\square

Proof of (a). By Lemma 1, (Rk+1,tk+1)(R_{k+1}, t_{k+1}) minimizes F(⋅,⋅,ck)F(\cdot, \cdot, c_k), and (Rk,tk)(R_k, t_k) is one candidate, so F(Rk+1,tk+1,ck)≤F(Rk,tk,ck)=ekF(R_{k+1}, t_{k+1}, c_k) \le F(R_k, t_k, c_k) = e_k. By Lemma 2 applied at the pose (Rk+1,tk+1)(R_{k+1}, t_{k+1}), ek+1=E(Rk+1,tk+1)≤F(Rk+1,tk+1,ck)e_{k+1} = E(R_{k+1}, t_{k+1}) \le F(R_{k+1}, t_{k+1}, c_k). □\square

Proof of (b). Suppose ICP does not stop at line L5 in the iterations 1,…,K1, \ldots, K after the first. With tol =0= 0 the test of line L5 fails only when ek−1−ek>0e_{k-1} - e_k > 0, so e0>e1>⋯>eKe_0 > e_1 > \cdots > e_K. Suppose cj=ckc_j = c_k for some j<k≤K−1j < k \le K - 1. FIT is a deterministic function of the match, so (Rj+1,tj+1)=(Rk+1,tk+1)(R_{j+1}, t_{j+1}) = (R_{k+1}, t_{k+1}), and then ej+1=ek+1e_{j+1} = e_{k+1}. This contradicts the strict decrease. So c0,…,cK−1c_0, \ldots, c_{K-1} are distinct maps from a set of nn elements to a set of mm elements, and K≤mnK \le m^n. So ICP stops at line L5 in some iteration k≤mn+1k \le m^n + 1, and line L3 runs at most mn+2m^n + 2 times (iterations 0,…,mn+10, \ldots, m^n + 1). □\square

Proof of (c). ICP stops at line L5 in iteration k≥1k \ge 1 in one of two cases.

Case ck=ck−1c_k = c_{k-1}. The returned pose is (Rk,tk)=FIT(ck−1)=FIT(ck)(R_k, t_k) = \mathrm{FIT}(c_{k-1}) = \mathrm{FIT}(c_k), which minimizes F(⋅,⋅,ck)F(\cdot, \cdot, c_k) by Lemma 1, and ckc_k is its closest-point match by line L3.

Case ek=ek−1e_k = e_{k-1}. By part (a), ek−1≥F(Rk,tk,ck−1)≥ek=ek−1e_{k-1} \ge F(R_k, t_k, c_{k-1}) \ge e_k = e_{k-1}, so F(Rk,tk,ck−1)=ek=E(Rk,tk)F(R_k, t_k, c_{k-1}) = e_k = E(R_k, t_k). Each term of F(Rk,tk,ck−1)F(R_k, t_k, c_{k-1}) is at least the matching term of E(Rk,tk)E(R_k, t_k), and the sums are equal, so every term is equal. Thus ck−1c_{k-1} is also a closest-point match of (Rk,tk)(R_k, t_k). It may differ from ckc_k only where line L3 breaks a tie. The returned pose (Rk,tk)=FIT(ck−1)(R_k, t_k) = \mathrm{FIT}(c_{k-1}) minimizes F(⋅,⋅,ck−1)F(\cdot, \cdot, c_{k-1}) by Lemma 1.

In both cases there is a closest-point match cc of the returned pose such that the returned pose minimizes F(⋅,⋅,c)F(\cdot, \cdot, c). In the first iteration (k=0k = 0) the test cannot hold, since e−1=∞e_{-1} = \infty and there is no previous match. □\square

Theorem. With tol =0= 0, ICP returns after finitely many iterations a pose (R,t)(R, t) with det⁡R=+1\det R = +1, the sequence of costs it meets never increases, and the returned pose is a fixed point of the two steps in the sense of (c).

Proof. Part (a) gives the monotone costs, part (b) the finite stop, and part (c) the fixed point property. The rotation is proper because each fit uses the sign fix of Lemma 1, and the start rotation is proper by assumption. ■\blacksquare

Remarks. The theorem does not say that the fixed point is a local minimum of EE. When a moved point is at the same distance from two target points, EE is not differentiable there, and the page gives an example where a small translation lowers EE although ICP has stopped. The theorem gives no rate and no global optimum. The bound mn+2m^n + 2 is a crude count of matches, not a statement about the usual number of iterations.

Complexity

The model is the real RAM. Line L3 with brute force computes nmn m squared distances, Θ(nm)\Theta(n m) time. Line L4 is Θ(n)\Theta(n). Line L6 forms HH in Θ(n)\Theta(n) time and then works on 3×33 \times 3 matrices in O(1)O(1) time, so it is Θ(n)\Theta(n). One iteration is therefore Θ(nm)\Theta(n m), and NN iterations cost Θ(Nnm)\Theta(N n m). The best case is two passes of line L3, Θ(nm)\Theta(n m). With a k-d tree on QQ, built once in O(mlog⁡m)O(m \log m) time, each query of line L3 takes logarithmic expected time on well-spread 3D data (the analysis of Friedman, Bentley and Finkel); this is not a worst-case bound. The extra space holds the moved points and the match, Θ(n)\Theta(n).

The number of iterations NN is a separate matter. The proof gives only N≤mn+2N \le m^n + 2, a crude count. The rate near a solution is linear (Pottmann et al. 2006), and the constant gets worse when the surfaces slide along each other. Measured iteration counts on real data are benchmark results, not bounds.

Properties

  • Monotone. The MSE never increases from step to step (lines L4 and L6).
  • Local. The result depends on the start pose. The example above has fixed points far from the truth.
  • Deterministic. With a fixed tie rule in line L3, the same input gives the same output.
  • Exact recovery without noise. If QQ contains R⋆pi+t⋆R^\star p_i + t^\star for every ii and the start is close enough, the matches become correct and line L6 returns (R⋆,t⋆)(R^\star, t^\star) exactly.
  • Not symmetric. Swapping PP and QQ changes the cost, because every source point must find a partner but not every target point is used.
  • Proper rotation. With the sign fix of line L6, det⁡R=+1\det R = +1 always.

Variants and improvements

  • Point-to-plane error. Point-to-plane ICP measures the distance along the target normal. It converges much faster on smooth surfaces.
  • Plane-to-plane error. Generalized ICP puts a covariance on each point and gives a maximum likelihood fit step.
  • Partial overlap. Trimmed ICP fits only the fraction ξ\xi of pairs with the least distances, which removes points without a partner.
  • Global optimum. Go-ICP wraps ICP in a branch and bound search over all poses and returns a pose within ϵ\epsilon of the global minimum.
  • Many small choices. Rusinkiewicz and Levoy sort the variants by stage: selection, matching, weighting, rejection, error metric and minimization; see efficient variants of ICP.
  • Robust weights. Weights from an M-estimator, solved by iteratively reweighted least squares, reduce the pull of far pairs.

When to use it

Use ICP when a rough pose is known, for example from odometry, from the previous frame of a depth camera, or from a feature match with RANSAC. It is simple, it has no parameters except the stop rule, and each step has a closed form. For surfaces sampled at different places, the point-to-plane form is usually faster. For clouds that only partly overlap, use trimming or a distance threshold. Without a rough pose, use a global method first: fast global registration, TEASER, 4PCS, or Go-ICP when a certificate of the optimum is needed. For 2D laser scans with a grid map, correlative scan matching searches over a window of poses instead.

Pitfalls

  • No sign fix in line L6. R←VUTR \leftarrow V U^{\mathsf T} from the SVD can return a reflection, with det⁡R=−1\det R = -1, for nearly planar or noisy pairs. Use R←Vdiag⁡(1,1,d) UTR \leftarrow V \operatorname{diag}(1, 1, d)\, U^{\mathsf T} with d=sign⁡det⁡(VUT)d = \operatorname{sign}\det(V U^{\mathsf T}).
  • The wrong direction of matching in line L3. Matching each target point to its closest source point and then fitting PP to QQ mixes two different costs, and the proof of monotone decrease fails. Match each moved source point Rpi+tR p_i + t to QQ.
  • The wrong cost in line L5. Comparing the cost after line L6 (with the old pairs) with the cost after line L3 (with the new pairs) mixes two quantities. Compare the values of line L4 of two iterations, as the pseudocode does.
  • A bad start. ICP has many fixed points. In the example, a start 90 degrees away ends 48 degrees off. Get a rough pose first.
  • Partial overlap. Points of PP with no true partner in QQ still get a closest point, and these pairs bias the fit. Reject pairs farther than a threshold, or use trimmed ICP.
  • Exact float tests. With tol =0= 0 in floating point, rounding can make ee rise by a tiny amount at the fixed point. Line L5 then stops, which is the right result; do not treat it as an error.

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()
iterative_closest_point.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-closest-point/. The authors are listed in prov/XFXA1G.jsonl.
"""Iterative closest point (ICP), the point-to-point form of Besl and McKay.

Given a source cloud P = [p_1, ..., p_n] and a target cloud Q = [q_1, ...,
q_m] in R^3, find a rotation R (det R = +1) and a translation t that bring
R p_i + t close to Q. Each iteration matches every moved source point to
its closest target point, then replaces (R, t) by the rigid motion that
best fits P to the matched points (the Kabsch step with the sign fix).
The mean squared distance never goes up, and the loop stops at a fixed
point of the match set or when the decrease is at most tol.

The closest-point search here is brute force, Theta(n m) per iteration. A
kd-tree on Q makes it about O(n log m) for points in 3D.
"""

from __future__ import annotations

from typing import List, Optional, Sequence, Tuple

from cvla import det, mul, svd, transpose

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


def transform(R: Sequence[Sequence[float]], t: Sequence[float],
              pts: Sequence[Sequence[float]]) -> List[Vector]:
    """The points R p + t."""
    r0, r1, r2 = R
    return [[r0[0] * p[0] + r0[1] * p[1] + r0[2] * p[2] + t[0],
             r1[0] * p[0] + r1[1] * p[1] + r1[2] * p[2] + t[1],
             r2[0] * p[0] + r2[1] * p[1] + r2[2] * p[2] + t[2]] for p in pts]


def closest_points(pts: Sequence[Sequence[float]],
                   target: Sequence[Sequence[float]]) -> Tuple[List[int], List[float]]:
    """For each point, the index of its closest target point and the squared
    distance to it. Brute force; ties go to the lowest index."""
    idx, d2 = [], []
    for x, y, z in pts:
        best, bj = float("inf"), -1
        for j, q in enumerate(target):
            dx, dy, dz = x - q[0], y - q[1], z - q[2]
            d = dx * dx + dy * dy + dz * dz
            if d < best:
                best, bj = d, j
        idx.append(bj)
        d2.append(best)
    return idx, d2


def mean_squared_error(R, t, P, Y) -> float:
    """(1/n) sum ||R p_i + t - y_i||^2 for paired lists P and Y."""
    moved = transform(R, t, P)
    return sum((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2
               for a, b in zip(moved, Y)) / len(P)


def best_rigid_transform(P: Sequence[Sequence[float]],
                         Y: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector]:
    """The rotation R (det R = +1) and translation t that minimize
    sum ||R p_i + t - y_i||^2 over paired points (Kabsch, with the sign fix
    R = V diag(1, 1, d) U^T, d = sign det(V U^T), where H = U S V^T)."""
    n = len(P)
    if n == 0 or n != len(Y):
        raise ValueError("best_rigid_transform: need two paired, nonempty lists")
    pc = [sum(p[k] for p in P) / n for k in range(3)]
    yc = [sum(y[k] for y in Y) / n for k in range(3)]
    H = [[0.0] * 3 for _ in range(3)]
    for p, y in zip(P, Y):
        a = [p[0] - pc[0], p[1] - pc[1], p[2] - pc[2]]
        b = [y[0] - yc[0], y[1] - yc[1], y[2] - yc[2]]
        for i in range(3):
            for j in range(3):
                H[i][j] += a[i] * b[j]
    U, _, V = svd(H)
    d = 1.0 if det(mul(V, transpose(U))) >= 0.0 else -1.0
    R = mul(mul(V, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, d]]), transpose(U))
    rp = [sum(R[i][k] * pc[k] for k in range(3)) for i in range(3)]
    return R, [yc[i] - rp[i] for i in range(3)]


def icp(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]],
        R0: Optional[Sequence[Sequence[float]]] = None,
        t0: Optional[Sequence[float]] = None,
        max_iter: int = 100, tol: float = 0.0) -> Tuple[Matrix, Vector, List[float]]:
    """Point-to-point ICP from the start pose (R0, t0) (default identity).

    Returns (R, t, costs). costs lists the mean squared error in the order
    the algorithm meets it: after each matching step, then after each fit
    step, so the list never goes up."""
    if len(P) == 0 or len(Q) == 0:
        raise ValueError("icp: empty point cloud")
    R = [list(r) for r in R0] if R0 is not None else [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]  # @line L1
    t = list(t0) if t0 is not None else [0.0, 0.0, 0.0]  # @line L1
    e_prev, prev = float("inf"), None  # @line L1
    costs: List[float] = []
    for _ in range(max_iter):  # @line L2
        idx, d2 = closest_points(transform(R, t, P), Q)  # @line L3
        e = sum(d2) / len(P)  # @line L4
        costs.append(e)
        if idx == prev or e_prev - e <= tol:  # @line L5
            return R, t, costs  # @line L5
        Y = [Q[j] for j in idx]
        R, t = best_rigid_transform(P, Y)  # @line L6
        costs.append(mean_squared_error(R, t, P, Y))
        e_prev, prev = e, idx  # @line L7
    return R, t, costs  # @line L8
test_iterative_closest_point.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-closest-point/. The authors are listed in prov/XFXA1G.jsonl.
import math
import random
import unittest

from cvgeom import add_noise, axis_angle_to_R, random_rotation
from cvla import det, mul, transpose
from iterative_closest_point import (best_rigid_transform, closest_points, icp,
                                     mean_squared_error, transform)

TOL_EXACT = 1e-9
TOL_ICP = 1e-6


def rot_angle(R1, R2):
    """The angle of the rotation R1^T R2, in radians: arccos((tr - 1) / 2),
    computed with atan2 so that it stays accurate for small angles."""
    m = mul(transpose(R1), R2)
    c = (m[0][0] + m[1][1] + m[2][2] - 1.0) / 2.0
    s = 0.5 * math.sqrt((m[2][1] - m[1][2]) ** 2 + (m[0][2] - m[2][0]) ** 2 + (m[1][0] - m[0][1]) ** 2)
    return math.atan2(s, c)


def cloud(rng, n):
    return [[rng.uniform(-1.0, 1.0) for _ in range(3)] for _ in range(n)]


def cost_with_best_t(R, P, Y):
    """The paired mean squared error of R with its best translation."""
    moved = transform(R, [0.0, 0.0, 0.0], P)
    t = [sum(y[k] for y in Y) / len(Y) - sum(p[k] for p in moved) / len(P) for k in range(3)]
    return mean_squared_error(R, t, P, Y)


class TestBestRigidTransform(unittest.TestCase):
    def test_exact_pairs(self):
        rng = random.Random(1)
        for _ in range(5):
            P = cloud(rng, 10)
            R = random_rotation(rng)
            t = [rng.uniform(-2, 2) for _ in range(3)]
            Rf, tf = best_rigid_transform(P, transform(R, t, P))
            self.assertLess(rot_angle(R, Rf), TOL_EXACT)
            self.assertLess(max(abs(a - b) for a, b in zip(t, tf)), TOL_EXACT)
            self.assertAlmostEqual(det(Rf), 1.0, places=12)

    def test_against_random_rotations(self):
        # Brute force: no sampled rotation, with its best translation, fits better.
        rng = random.Random(2)
        P = cloud(rng, 12)
        Y = add_noise(rng, transform(random_rotation(rng), [0.3, -0.2, 0.5], P), 0.05)
        Rf, tf = best_rigid_transform(P, Y)
        best = mean_squared_error(Rf, tf, P, Y)
        for _ in range(2000):
            R = random_rotation(rng)
            self.assertGreaterEqual(cost_with_best_t(R, P, Y), best - 1e-12)

    def test_sign_fix_on_mirror_image(self):
        # The target is a mirror image of the source. Without the sign fix the
        # SVD gives a reflection; with it the result is a proper rotation.
        rng = random.Random(3)
        P = cloud(rng, 8)
        Y = [[-p[0], p[1], p[2]] for p in P]
        Rf, tf = best_rigid_transform(P, Y)
        self.assertAlmostEqual(det(Rf), 1.0, places=12)
        rtr = mul(transpose(Rf), Rf)
        for i in range(3):
            for j in range(3):
                self.assertAlmostEqual(rtr[i][j], 1.0 if i == j else 0.0, places=12)
        best = mean_squared_error(Rf, tf, P, Y)
        for _ in range(1000):
            R = random_rotation(rng)
            self.assertGreaterEqual(cost_with_best_t(R, P, Y), best - 1e-12)


class TestICP(unittest.TestCase):
    def test_exact_recovery_without_noise(self):
        rng = random.Random(4)
        P = cloud(rng, 40)
        R = axis_angle_to_R([1.0, 2.0, -1.0], math.radians(15.0))
        t = [0.1, -0.05, 0.08]
        Q = transform(R, t, P)
        rng.shuffle(Q)
        Rf, tf, costs = icp(P, Q)
        self.assertLess(rot_angle(R, Rf), TOL_ICP)
        self.assertLess(max(abs(a - b) for a, b in zip(t, tf)), TOL_ICP)
        self.assertLess(costs[-1], 1e-12)
        self.assertAlmostEqual(det(Rf), 1.0, places=12)

    def test_cost_never_goes_up(self):
        rng = random.Random(5)
        P = cloud(rng, 30)
        R = axis_angle_to_R([0.0, 1.0, 1.0], math.radians(25.0))
        Q = add_noise(rng, transform(R, [0.2, 0.1, -0.1], P), 0.02) + cloud(rng, 15)
        _, _, costs = icp(P, Q, max_iter=200)
        for a, b in zip(costs, costs[1:]):
            self.assertLessEqual(b, a + 1e-12)
        self.assertLess(len(costs), 2 * 200)

    def test_stops_at_a_fixed_point(self):
        rng = random.Random(6)
        P = cloud(rng, 25)
        Q = add_noise(rng, transform(axis_angle_to_R([1, 0, 0], 0.3), [0, 0.1, 0], P), 0.03)
        Rf, tf, _ = icp(P, Q, max_iter=500)
        idx, _ = closest_points(transform(Rf, tf, P), Q)
        R2, t2 = best_rigid_transform(P, [Q[j] for j in idx])
        self.assertLess(rot_angle(Rf, R2), 1e-9)
        self.assertLess(max(abs(a - b) for a, b in zip(tf, t2)), 1e-9)

    def test_local_minimum_from_a_far_start(self):
        # ICP is local: from the identity, 90 degrees away, it stops at a
        # fixed point with a positive cost and a wrong rotation.
        rng = random.Random(7)
        P = cloud(rng, 30)
        R = axis_angle_to_R([0.3, -1.0, 0.4], math.radians(90.0))
        Q = transform(R, [0.5, 0.0, -0.3], P)
        Rf, _, costs = icp(P, Q)
        self.assertGreater(costs[-1], 0.1)
        self.assertGreater(rot_angle(R, Rf), 1.0)

    def test_start_pose_is_used(self):
        rng = random.Random(7)
        P = cloud(rng, 30)
        R = axis_angle_to_R([0.3, -1.0, 0.4], math.radians(150.0))
        t = [0.5, 0.0, -0.3]
        Q = transform(R, t, P)
        Rf, tf, costs = icp(P, Q, R0=axis_angle_to_R([0.3, -1.0, 0.4], math.radians(140.0)), t0=t)
        self.assertLess(rot_angle(R, Rf), TOL_ICP)
        self.assertLess(costs[-1], 1e-12)


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

History

Besl and McKay published ICP in 1992 in IEEE TPAMI, for registering free-form shapes such as point sets, curves and surfaces. They used Horn's 1987 quaternion solution for the fit step and proved that the mean square error converges monotonically. Chen and Medioni presented a close method at ICRA in 1991 and in Image and Vision Computing in 1992, with the distance to the tangent plane of the target. Zhang's method, in a 1992 report and in IJCV in 1994, used a k-d tree and a statistical rule that rejects far pairs. The SVD solution of the fit step goes back to Arun, Huang and Blostein (1987), and Umeyama (1991) fixed its reflection case. Rusinkiewicz and Levoy (2001) compared the many variants and gave a fast combination.

References

  1. 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 statement of the ICP algorithm, the closed-form registration step by unit quaternions, and the theorem that the mean square error decreases monotonically and converges
  2. Yang Chen and Gérard Medioni, Object modelling by registration of multiple range images, Image and Vision Computing 10(3), 1992, 145-155, The iterative registration of range images with the point-to-plane error, a method developed at the same time as ICP
  3. Zhengyou Zhang, Iterative point matching for registration of free-form curves and surfaces, International Journal of Computer Vision 13(2), 1994, 119-152, The iterative matching with a k-d tree for the closest points and a statistical threshold that rejects far pairs
  4. K. S. Arun, Thomas S. Huang and Steven D. Blostein, Least-squares fitting of two 3-D point sets, IEEE Transactions on Pattern Analysis and Machine Intelligence 9(5), 1987, 698-700, The SVD solution of the rotation for matched points, and the degenerate case where it returns a reflection
  5. Shinji Umeyama, Least-squares estimation of transformation parameters between two point patterns, IEEE Transactions on Pattern Analysis and Machine Intelligence 13(4), 1991, 376-380, The main theorem: the optimal rotation V diag(1, 1, d) U^T with the sign of the determinant, which fixes the reflection case
  6. Berthold K. P. Horn, Closed-form solution of absolute orientation using unit quaternions, Journal of the Optical Society of America A 4(4), 1987, 629-642, The best rotation as the eigenvector of the largest eigenvalue of a 4 by 4 symmetric matrix, used by Besl and McKay for the fit step
  7. Helmut Pottmann, Qi-Xing Huang, Yong-Liang Yang and Shi-Min Hu, Geometry and convergence analysis of algorithms for registration of 3D shapes, International Journal of Computer Vision 67(3), 2006, 277-296, The convergence analysis of ICP: linear convergence near a zero-residual solution
  8. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 13.2.1, Range data merging (ICP and its variants)

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