Algorithm Search⌘K

Algorithmcore

Point-to-plane ICP

Also called Chen-Medioni ICP.

ICP that minimizes the squared distance from each moved source point to the tangent plane of its target match, by a Gauss-Newton step on a 6 by 6 linear system. Fast near the solution; 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
Yang Chen, Gérard Medioni, 1991

Point-to-plane ICP aligns a source point cloud PP to a target cloud QQ that has a unit normal at each point. It is iterative closest point with another error: instead of the distance from a moved source point to its matched target point, it measures the distance to the tangent plane through the target point, ri=ni⋅(Rpi+t−qi)r_i = n_i \cdot (R p_i + t - q_i). Each iteration matches by closest point, then takes one Gauss-Newton step on ∑iri2\sum_i r_i^2: a small rotation ww and a translation uu from a 6×66 \times 6 linear system, applied as an exact rigid motion. A point may slide along the target surface at no cost, so the method does not fight the sampling of the two clouds. Near the solution it converges much faster than point-to-point ICP, but it is still a local method and needs a good start.

In plain words

Two scans of a surface never sample the same spots. Plain ICP pulls each point toward one sample of the other scan, even when the point already lies on the surface between two samples. That pull is wrong, and it slows ICP down.

Point-to-plane ICP measures only how far a point is off the surface, along the surface normal. Moving a point along the surface costs nothing. The error then depends on the motion in a nearly linear way. One small linear system with six unknowns, three for the turn and three for the slide, gives a good step. Near the answer, each step roughly squares the remaining error.

The method needs normals on the target. If the target is flat, sliding along it costs nothing in every direction of the plane, and the system has no unique answer.

The problem

Input. A source cloud P=(p1,…,pn)P = (p_1, \ldots, p_n), a target cloud Q={q1,…,qm}Q = \{q_1, \ldots, q_m\} in R3\mathbb{R}^3, a unit normal νj\nu_j for each qjq_j, a start pose (R0,t0)(R_0, t_0) with R0∈SO(3)R_0 \in SO(3), and a tolerance tol. The normals usually come from normal estimation; their sign does not matter, because the residual is squared.

Output. A pose (R,t)(R, t), R∈SO(3)R \in SO(3), at which the point-to-plane cost

Epl(R,t)=∑i=1n(ni⋅(Rpi+t−yi))2E_{\text{pl}}(R, t) = \sum_{i=1}^{n} \big(n_i \cdot (R p_i + t - y_i)\big)^2

is stationary for its closest-point match, where yiy_i is the closest target point of Rpi+tR p_i + t and nin_i its normal. As for ICP, the goal is a pose near the true one; the method does not promise a global minimum.

The algorithm

Write xi=Rpi+tx_i = R p_i + t for the moved points. Turning by a small vector ww (the angle ∣w∣|w| about the axis w/∣w∣w / |w|) and moving by uu maps xix_i to xi+w×xi+ux_i + w \times x_i + u to first order, and ni⋅(w×xi)=(xi×ni)⋅wn_i \cdot (w \times x_i) = (x_i \times n_i) \cdot w. So the residual becomes ri+aiTzr_i + a_i^{\mathsf T} z with z=(w,u)z = (w, u) and ai=(xi×ni, ni)∈R6a_i = (x_i \times n_i,\ n_i) \in \mathbb{R}^6. The step minimizes ∑i(ri+aiTz)2\sum_i (r_i + a_i^{\mathsf T} z)^2, which by the normal equations is Az=bA z = b with A=∑iaiaiTA = \sum_i a_i a_i^{\mathsf T} and b=−∑iriaib = -\sum_i r_i a_i. This is one Gauss-Newton step for the residuals rir_i as functions of zz.

  1. POINT-TO-PLANE-ICP(P, Q, ν, R0, t0, tol)
  2. 1R ← R0 ; t ← t0
  3. 2repeat (up to an iteration cap)
  4. 3x_i ← R p_i + t ; c(i) ← closest target index ; y_i ← q_c(i) ; n_i ← ν_c(i)
  5. 4r_i ← n_i · (x_i - y_i) ; record Σ_i r_i²
  6. 5solve A z = b, A = Σ a_i a_iᵀ, b = -Σ r_i a_i, a_i = (x_i × n_i, n_i), z = (w, u)
  7. 6R ← Exp(w) R ; t ← Exp(w) t + u
  8. 7if |z| ≤ tol then stop
  9. 8return R, t

Line L3 is the same closest-point step as in ICP; the code uses brute force, and a k-d tree is the usual choice. Line L5 builds the 6×66 \times 6 symmetric matrix AA and solves it by Gaussian elimination. Line L6 applies the rotation Exp⁡(w)\operatorname{Exp}(w) of the vector ww by the Rodrigues formula, so RR stays a rotation; the new moved points are exactly Exp⁡(w)xi+u\operatorname{Exp}(w) x_i + u. Line L7 stops when the step is tiny.

Example

The target is a 15×1515 \times 15 grid on the surface z=0.3sin⁡(2x)cos⁡(1.5y)+0.1x2z = 0.3 \sin(2x) \cos(1.5y) + 0.1 x^2 over [−1,1]2[-1, 1]^2, with the exact normals, 225 points. The source is 60 of these points (chosen with seed 1), moved by the inverse of a rotation of 10 degrees about the axis (1,2,3)(1, 2, 3) and the translation (0.05,−0.03,0.04)(0.05, -0.03, 0.04). The start pose is the identity. Coordinates are unitless.

iteration point-to-plane cost after L4
1 0.458
2 0.00139
3 1.01e-7
4 1.87e-17
5 9.41e-32

The final rotation differs from the true one by 6×10−176 \times 10^{-17} radians, which is rounding error. The square roots of the costs are 0.68, 0.037, 3.2e-4, 4.3e-9 and 9.7e-16: each one is about a constant times the square of the one before, the mark of quadratic convergence.

Point-to-point ICP on the same scene, from the same start, behaves differently. Its mean squared error falls from 0.0122 to 0.00342 in 10 fit steps, and then it stops at a fixed point that is 4.26 degrees off. Point-to-point ICP pulls each point to one target sample, and on this scene the pulls toward wrong samples balance at the wrong pose. Point-to-plane ICP lets a point slide along the surface, so these pulls do not occur.

Correctness

The proof in proofs/correctness.md shows four facts. The change of the residual under the motion x↦Exp⁡(w)x+ux \mapsto \operatorname{Exp}(w) x + u is aiTza_i^{\mathsf T} z plus a remainder of at most 12∣w∣2∣xi∣\frac12 |w|^2 |x_i|. Line L5 returns the unique minimizer of the linearized cost when AA is nonsingular, and no unique minimizer exists when AA is singular. Line L6 keeps RR a rotation. A zero step means that the fixed-match cost is stationary, and the true pose of an exact copy gives zero residuals and a zero step, so it is a fixed point. The proof does not show a decrease in every iteration: a full Gauss-Newton step can overshoot.

Pottmann, Huang, Yang and Hu (2006) show that the tangent plane method is a Gauss-Newton method on the squared distance function of the target surface and, for a zero-residual problem with a good start, converges quadratically. Point-to-point ICP converges only linearly. The page cites these results and does not prove them.

Proof: The point-to-plane step solves the linearized problem and keeps a rotationfull

We use the notation of the page. The source is P=(p1,…,pn)P = (p_1, \ldots, p_n), the target is Q={q1,…,qm}Q = \{q_1, \ldots, q_m\}, and νj\nu_j is the unit normal at qjq_j. In one iteration the moved points are xi=Rpi+tx_i = R p_i + t, line L3 picks the closest target point qc(i)q_{c(i)} of xix_i and writes yi=qc(i)y_i = q_{c(i)} and ni=νc(i)n_i = \nu_{c(i)}. The residual is ri=ni⋅(xi−yi)r_i = n_i \cdot (x_i - y_i) and the cost of line L4 is ∑iri2\sum_i r_i^2. For w,u∈R3w, u \in \mathbb{R}^3 let Exp⁡(w)\operatorname{Exp}(w) be the rotation by the angle ∣w∣|w| about the axis w/∣w∣w/|w| (the identity for w=0w = 0), given by the Rodrigues formula. Let

ai=(xi×nini)∈R6,A=∑iaiaiT,b=−∑iriai.a_i = \begin{pmatrix} x_i \times n_i \\ n_i \end{pmatrix} \in \mathbb{R}^6, \qquad A = \sum_i a_i a_i^{\mathsf T}, \qquad b = -\sum_i r_i a_i .

Claim. In each iteration, with the match cc fixed:

  1. For the motion x↦Exp⁡(w)x+ux \mapsto \operatorname{Exp}(w) x + u, the new residual is ri(w,u)=ri+aiT(w,u)+ρir_i(w, u) = r_i + a_i^{\mathsf T} (w, u) + \rho_i with ∣ρi∣≤12∣w∣2∣xi∣|\rho_i| \le \tfrac12 |w|^2 |x_i|.
  2. If AA is nonsingular, line L5 returns the unique minimizer of the linearized cost ℓ(w,u)=∑i(ri+aiT(w,u))2\ell(w, u) = \sum_i (r_i + a_i^{\mathsf T}(w, u))^2. If AA is singular, the linearized cost has no unique minimizer, and the code raises an error.
  3. Line L6 keeps R∈SO(3)R \in SO(3), and the new moved points are exactly Exp⁡(w)xi+u\operatorname{Exp}(w) x_i + u.
  4. The returned step is zero if and only if ∑iriai=0\sum_i r_i a_i = 0, which is the condition that the fixed-match cost ∑iri(w,u)2\sum_i r_i(w, u)^2 is stationary at (w,u)=(0,0)(w, u) = (0, 0). If every ri=0r_i = 0, the step is zero.

Lemma 1 (first order expansion). For every x,n,y∈R3x, n, y \in \mathbb{R}^3 with ∣n∣=1|n| = 1 and every w,uw, u,

n⋅(Exp⁡(w)x+u−y)=n⋅(x−y)+(x×n)⋅w+n⋅u+ρ,∣ρ∣≤12∣w∣2∣x∣.n \cdot (\operatorname{Exp}(w) x + u - y) = n \cdot (x - y) + (x \times n) \cdot w + n \cdot u + \rho, \qquad |\rho| \le \tfrac12 |w|^2 |x| .

Proof. Let θ=∣w∣\theta = |w|. The Rodrigues formula gives Exp⁡(w)x=x+sin⁡θθ(w×x)+1−cos⁡θθ2 w×(w×x)\operatorname{Exp}(w) x = x + \frac{\sin\theta}{\theta} (w \times x) + \frac{1 - \cos\theta}{\theta^2}\, w \times (w \times x) for θ>0\theta > 0. So Exp⁡(w)x−x−w×x=(sin⁡θθ−1)(w×x)+1−cos⁡θθ2 w×(w×x)\operatorname{Exp}(w) x - x - w \times x = \big(\frac{\sin\theta}{\theta} - 1\big) (w \times x) + \frac{1 - \cos\theta}{\theta^2}\, w \times (w \times x). Let x⊥x_\perp be the part of xx orthogonal to ww. The two terms are orthogonal, with lengths (1−sin⁡θθ) θ∣x⊥∣(1 - \frac{\sin\theta}{\theta})\, \theta |x_\perp| and (1−cos⁡θ)∣x⊥∣(1 - \cos\theta) |x_\perp|. The square of the length of the sum is ∣x⊥∣2((θ−sin⁡θ)2+(1−cos⁡θ)2)=∣x⊥∣2(θ2+2−2cos⁡θ−2θsin⁡θ)|x_\perp|^2 \big((\theta - \sin\theta)^2 + (1 - \cos\theta)^2\big) = |x_\perp|^2 \big(\theta^2 + 2 - 2\cos\theta - 2\theta\sin\theta\big). The function g(θ)=θ4/4−θ2−2+2cos⁡θ+2θsin⁡θg(\theta) = \theta^4/4 - \theta^2 - 2 + 2\cos\theta + 2\theta\sin\theta has g(0)=0g(0) = 0 and g′(θ)=θ3−2θ+2θcos⁡θ=θ(θ2−2+2cos⁡θ)≥0g'(\theta) = \theta^3 - 2\theta + 2\theta\cos\theta = \theta(\theta^2 - 2 + 2\cos\theta) \ge 0, because cos⁡θ≥1−θ2/2\cos\theta \ge 1 - \theta^2/2. So the length is at most 12θ2∣x⊥∣≤12∣w∣2∣x∣\tfrac12 \theta^2 |x_\perp| \le \tfrac12 |w|^2 |x|. Finally n⋅(w×x)=w⋅(x×n)n \cdot (w \times x) = w \cdot (x \times n) by the cyclic rule of the triple product, and ∣n∣=1|n| = 1 bounds the dot product of nn with the remainder. For w=0w = 0 the remainder is 0. □\square

Proof of 1. Apply Lemma 1 with x=xix = x_i, y=yiy = y_i, n=nin = n_i. □\square

Proof of 2. ℓ\ell is the squared length of Mz+rM z + r, where MM is the n×6n \times 6 matrix with rows aiTa_i^{\mathsf T}, z=(w,u)z = (w, u) and r=(r1,…,rn)r = (r_1, \ldots, r_n). A vector zz minimizes ℓ\ell if and only if it solves the normal equations MTMz=−MTrM^{\mathsf T} M z = -M^{\mathsf T} r, that is Az=bA z = b. If A=MTMA = M^{\mathsf T} M is nonsingular, the solution is unique, and line L5 computes it by Gaussian elimination. If AA is singular, there is z0≠0z_0 \ne 0 with Mz0=0M z_0 = 0, and ℓ(z+sz0)=ℓ(z)\ell(z + s z_0) = \ell(z) for every ss, so no minimizer is unique. □\square

Proof of 3. Exp⁡(w)\operatorname{Exp}(w) is a rotation, and the product of two rotations is a rotation, so R′=Exp⁡(w)R∈SO(3)R' = \operatorname{Exp}(w) R \in SO(3). With t′=Exp⁡(w)t+ut' = \operatorname{Exp}(w) t + u, R′pi+t′=Exp⁡(w)(Rpi+t)+u=Exp⁡(w)xi+uR' p_i + t' = \operatorname{Exp}(w)(R p_i + t) + u = \operatorname{Exp}(w) x_i + u. □\square

Proof of 4. If AA is nonsingular, z=A−1bz = A^{-1} b is zero exactly when b=0b = 0. The gradient of ∑iri(w,u)2\sum_i r_i(w, u)^2 at (0,0)(0, 0) is 2∑iriai2 \sum_i r_i a_i by part 1, since the remainders ρi\rho_i are of second order in ww. If every ri=0r_i = 0, then b=0b = 0 and the step is zero. □\square

Theorem. Each iteration of POINT-TO-PLANE-ICP takes the Gauss-Newton step of the fixed-match point-to-plane cost, parametrized by (w,u)(w, u) around the current pose, and applies it as an exact rigid motion. The returned RR is a rotation. If the loop stops by line L7 with tol =0= 0, the current pose is a stationary point of the point-to-plane cost for its closest-point match. If the source is an exact rigid copy of points of the target, so that each moved point coincides with its target point at the true pose, then the true pose gives zero residuals and a zero step, so it is a fixed point of the iteration.

Proof. The Jacobian of the residual vector at (0,0)(0, 0) has rows aiTa_i^{\mathsf T} by part 1, so the Gauss-Newton step is the minimizer of ℓ\ell, which line L5 computes by part 2. Part 3 gives the rotation and the exact motion. Part 4 gives the stationary point and the fixed point. At the true pose of an exact copy, each moved point is a target point, so its closest target point is itself, at distance 0, and ri=0r_i = 0. ■\blacksquare

What this proof does not give. It does not show that the cost falls in every iteration: a full Gauss-Newton step can overshoot, and the match can change. It gives no rate. Pottmann, Huang, Yang and Hu (2006) show that the method is a Gauss-Newton method for the squared distance function, with quadratic convergence for a zero-residual problem from a good start; the page cites that result and does not prove it.

Complexity

The model is the real RAM. Per iteration, line L3 costs Θ(nm)\Theta(n m) by brute force. Line L4 is Θ(n)\Theta(n). Line L5 adds nn outer products of 6-vectors, Θ(n)\Theta(n), and solves a 6×66 \times 6 system in O(1)O(1) time. Line L6 is O(1)O(1). So one iteration is Θ(nm)\Theta(n m), and NN iterations cost Θ(Nnm)\Theta(N n m); the best case is one iteration with a zero step, Θ(nm)\Theta(n m). With a k-d tree on QQ, line L3 drops to about nlog⁡mn \log m on typical 3D data (an expected cost, not a worst case). The extra space holds the moved points, the match and the 6×66 \times 6 system, Θ(n)\Theta(n).

The number of iterations NN has no useful worst-case bound. The local rate is quadratic for zero residual (Pottmann et al. 2006). The measured gap to point-to-point ICP depends on the data; Rusinkiewicz and Levoy (2001) report fewer iterations for point-to-plane on their test meshes, which is a benchmark result.

Properties

  • Gauss-Newton. Each iteration is one Gauss-Newton step on the fixed-match residuals, with an exact rotation update.
  • Fast local rate. Quadratic near a zero-residual solution from a good start, against linear for point-to-point ICP.
  • Not monotone. Without a line search, the cost can rise in an iteration far from the solution.
  • Local. Like all ICP forms, the result depends on the start pose.
  • Needs normals. Normals on the target only; the source needs none.
  • Degenerate geometry. If the target is a plane, a cylinder or another surface that can slide on itself, AA is singular or nearly singular.

Variants and improvements

  • Symmetric error. Using the normals of both clouds, as in the symmetric objective of Rusinkiewicz (2019), widens the region of fast convergence.
  • Plane-to-plane. Generalized ICP puts a flat covariance on each point of both clouds; point-to-plane is a limit case of it.
  • Damping. Adding λI\lambda I to AA gives a Levenberg-Marquardt step, which handles near-singular AA and large first steps.
  • Robust weights. Weights wiw_i on the residuals, from an M-estimator, turn the step into iteratively reweighted least squares.
  • Normal-space sampling. Rusinkiewicz and Levoy choose source points so that the normals spread over all directions, which keeps AA well conditioned; see efficient variants of ICP.

When to use it

Use point-to-plane ICP for smooth surfaces sampled by depth cameras, laser scanners or stereo, when normals are cheap to get and a rough pose is known. KinectFusion (Newcombe et al. 2011), for example, tracks its depth camera with point-to-plane ICP. Use point-to-point ICP when normals are unreliable, for example on sparse or very noisy clouds, or when the clouds have no surface. Use generalized ICP when both clouds are surfaces and you want a symmetric, probabilistic error. For partial overlap, add a distance threshold or trimming.

Pitfalls

  • Line L6 with t←t+ut \leftarrow t + u. The step turns all moved points about the origin, so the translation must turn too: t←Exp⁡(w) t+ut \leftarrow \operatorname{Exp}(w)\, t + u. With t+ut + u the pose drifts whenever t≠0t \ne 0.
  • Line L6 with R←(I+[w]×)RR \leftarrow (I + [w]_\times) R. The first-order matrix is not a rotation, and the error grows over the iterations. Use Exp⁡(w)\operatorname{Exp}(w), or orthogonalize the result.
  • A singular system in line L5. A planar target lets the source slide in two directions and turn about the normal, so AA has rank 3. Check the rank or the smallest eigenvalue of AA, sample points with varied normals, or add damping.
  • Bad normals in line L3. Normals from a neighborhood that crosses an edge or two sheets of the surface point the wrong way. The residuals are then wrong, not only noisy. Use a neighborhood size that fits the sampling.
  • A far start. The fast rate is local. From a far start the step can overshoot; bound the step or add a line search.

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()
point_to_plane_icp.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/point-to-plane-icp/. The authors are listed in prov/FSJANG.jsonl.
"""Point-to-plane ICP (Chen and Medioni), with the linear step of Low.

Given a source cloud P, a target cloud Q and a unit normal N[j] for each
target point, find a rotation R (det R = +1) and a translation t that make
sum_i (n_i . (R p_i + t - q_i))^2 small, where q_i is the closest target
point of R p_i + t and n_i its normal. Each iteration matches by closest
point, then takes one Gauss-Newton step: the small rotation w and the
translation u that minimize the linearized error, found from a 6 x 6
linear system. The rotation is applied as the exact rotation of the vector
w (Rodrigues formula), so R stays a rotation.

The closest-point search is brute force, Theta(n m) per iteration.
"""

from __future__ import annotations

from typing import List, Optional, Sequence, Tuple

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

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


def transform(R, t, pts) -> List[Vector]:
    """The points R p + t."""
    return [[sum(R[i][k] * p[k] for k in range(3)) + t[i] for i in range(3)] for p in pts]


def closest_points(pts, target) -> List[int]:
    """For each point, the index of its closest target point (brute force;
    ties go to the lowest index)."""
    idx = []
    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)
    return idx


def plane_error(moved, targets, normals) -> float:
    """sum_i (n_i . (x_i - q_i))^2 for paired lists."""
    return sum(sum(n[k] * (x[k] - q[k]) for k in range(3)) ** 2
               for x, q, n in zip(moved, targets, normals))


def linearized_step(moved, targets, normals) -> Vector:
    """The vector (w, u) of 6 numbers that minimizes
    sum_i (r_i + (x_i x n_i) . w + n_i . u)^2, with r_i = n_i . (x_i - q_i).
    This is the error after the motion x -> x + w x x + u, to first order.
    Raises ValueError if the 6 x 6 normal matrix is exactly singular (for
    example when all points lie on one plane)."""
    A = [[0.0] * 6 for _ in range(6)]
    b = [0.0] * 6
    for x, q, n in zip(moved, targets, normals):
        c = [x[1] * n[2] - x[2] * n[1], x[2] * n[0] - x[0] * n[2], x[0] * n[1] - x[1] * n[0]]
        a = c + [n[0], n[1], n[2]]
        r = n[0] * (x[0] - q[0]) + n[1] * (x[1] - q[1]) + n[2] * (x[2] - q[2])
        for i in range(6):
            b[i] -= a[i] * r
            for j in range(6):
                A[i][j] += a[i] * a[j]
    try:
        return solve(A, b)
    except ValueError:
        raise ValueError("point_to_plane: the geometry does not fix all six degrees of freedom")


def point_to_plane_icp(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]],
                       N: Sequence[Sequence[float]],
                       R0: Optional[Sequence[Sequence[float]]] = None,
                       t0: Optional[Sequence[float]] = None,
                       max_iter: int = 50, tol: float = 1e-12) -> Tuple[Matrix, Vector, List[float]]:
    """Point-to-plane ICP from the start pose (R0, t0) (default identity).
    N[j] is the unit normal of Q[j]. Stops when the step (w, u) has norm at
    most tol. Returns (R, t, costs), where costs[k] is the point-to-plane
    error after the matching step of iteration k."""
    if len(P) == 0 or len(Q) == 0 or len(N) != len(Q):
        raise ValueError("point_to_plane_icp: bad input sizes")
    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
    costs: List[float] = []
    for _ in range(max_iter):  # @line L2
        moved = transform(R, t, P)
        idx = closest_points(moved, Q)  # @line L3
        targets, normals = [Q[j] for j in idx], [N[j] for j in idx]  # @line L3
        costs.append(plane_error(moved, targets, normals))  # @line L4
        x = linearized_step(moved, targets, normals)  # @line L5
        dR = axis_angle_to_R(x[:3])  # @line L6
        R = mul(dR, R)  # @line L6
        t = [v + u for v, u in zip(matvec(dR, t), x[3:])]  # @line L6
        if sum(v * v for v in x) <= tol * tol:  # @line L7
            break  # @line L7
    return R, t, costs  # @line L8
test_point_to_plane_icp.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/point-to-plane-icp/. The authors are listed in prov/FSJANG.jsonl.
import math
import random
import unittest

from cvgeom import add_noise, axis_angle_to_R
from cvla import det, mul, transpose
from point_to_plane_icp import (closest_points, linearized_step, plane_error,
                                point_to_plane_icp, transform)

TOL_ICP = 1e-6


def rot_angle(R1, R2):
    """The angle of R1^T R2: arccos((tr - 1) / 2), computed with atan2."""
    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 surface(k=15):
    """Grid points on z = 0.3 sin(2x) cos(1.5y) + 0.1 x^2 over [-1, 1]^2,
    with their exact unit normals."""
    g = [-1.0 + 2.0 * i / (k - 1) for i in range(k)]
    Q, N = [], []
    for x in g:
        for y in g:
            Q.append([x, y, 0.3 * math.sin(2 * x) * math.cos(1.5 * y) + 0.1 * x * x])
            fx = 0.6 * math.cos(2 * x) * math.cos(1.5 * y) + 0.2 * x
            fy = -0.45 * math.sin(2 * x) * math.sin(1.5 * y)
            s = math.sqrt(fx * fx + fy * fy + 1.0)
            N.append([-fx / s, -fy / s, 1.0 / s])
    return Q, N


def source_from(Q, sel, R, t):
    """Points p with R p + t = q for the selected target points q."""
    Rt = transpose(R)
    return [[sum(Rt[i][k] * (Q[j][k] - t[k]) for k in range(3)) for i in range(3)] for j in sel]


class TestPointToPlane(unittest.TestCase):
    def setUp(self):
        self.Q, self.N = surface()
        self.rng = random.Random(1)
        self.sel = self.rng.sample(range(len(self.Q)), 60)
        self.R = axis_angle_to_R([1.0, 2.0, 3.0], math.radians(10.0))
        self.t = [0.05, -0.03, 0.04]
        self.P = source_from(self.Q, self.sel, self.R, self.t)

    def test_exact_recovery_without_noise(self):
        Rf, tf, costs = point_to_plane_icp(self.P, self.Q, self.N)
        self.assertLess(rot_angle(self.R, Rf), TOL_ICP)
        self.assertLess(max(abs(a - b) for a, b in zip(self.t, tf)), TOL_ICP)
        self.assertAlmostEqual(det(Rf), 1.0, places=12)
        self.assertLess(costs[-1], 1e-20)

    def test_fast_final_convergence(self):
        # Zero residual and a near start: each error is at most the square of
        # the one before (a check of this scene, not a general bound).
        _, _, costs = point_to_plane_icp(self.P, self.Q, self.N)
        for a, b in zip(costs, costs[1:]):
            if a > 1e-12:
                self.assertLessEqual(b, a * a)

    def test_linear_step_is_the_least_squares_minimum(self):
        # Brute force: random changes of the step never lower the linear cost.
        moved = transform(axis_angle_to_R([0.0, 1.0, 0.0], 0.05), [0.02, 0.0, 0.0], self.P)
        idx = closest_points(moved, self.Q)
        tg, nm = [self.Q[j] for j in idx], [self.N[j] for j in idx]
        x = linearized_step(moved, tg, nm)

        def lin_cost(v):
            total = 0.0
            for p, q, n in zip(moved, tg, nm):
                c = [p[1] * n[2] - p[2] * n[1], p[2] * n[0] - p[0] * n[2], p[0] * n[1] - p[1] * n[0]]
                r = sum(n[k] * (p[k] - q[k]) for k in range(3))
                total += (r + sum(c[k] * v[k] for k in range(3)) + sum(n[k] * v[3 + k] for k in range(3))) ** 2
            return total

        best = lin_cost(x)
        rng = random.Random(2)
        for _ in range(300):
            y = [v + rng.gauss(0.0, 1e-3) for v in x]
            self.assertGreaterEqual(lin_cost(y), best - 1e-15)

    def test_plane_is_degenerate(self):
        g = [i / 4.0 for i in range(5)]
        Q = [[x, y, 0.0] for x in g for y in g]
        N = [[0.0, 0.0, 1.0]] * len(Q)
        P = [[x + 0.01, y, 0.02] for x, y, _ in Q]
        with self.assertRaises(ValueError):
            point_to_plane_icp(P, Q, N)

    def test_noisy_source(self):
        P = add_noise(self.rng, self.P, 0.005)
        Rf, tf, costs = point_to_plane_icp(P, self.Q, self.N)
        self.assertLess(rot_angle(self.R, Rf), math.radians(1.0))
        self.assertLess(max(abs(a - b) for a, b in zip(self.t, tf)), 0.02)
        self.assertLess(costs[-1], costs[0])
        moved = transform(Rf, tf, P)
        idx = closest_points(moved, self.Q)
        e = plane_error(moved, [self.Q[j] for j in idx], [self.N[j] for j in idx])
        self.assertLessEqual(e, costs[0])


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

History

Chen and Medioni presented the method at ICRA in 1991 and in Image and Vision Computing in 1992, for building object models from several range images. They paired a point with the place where the line along its normal meets the other surface, and minimized the distances to the tangent planes there. The closest-point pairing, shared with Besl and McKay's ICP of 1992, became the common form later. Low (2004) wrote the small-angle step as one linear least squares problem in six unknowns. Pottmann, Huang, Yang and Hu (2006) explained the fast convergence: the method is a Gauss-Newton iteration on the squared distance function of the target.

References

  1. Yang Chen and Gérard Medioni, Object modelling by registration of multiple range images, Image and Vision Computing 10(3), 1992, 145-155, The registration error as the distance from a point to the tangent plane of the other surface, the iterative least squares solution, and the pairs found along the surface normal
  2. Kok-Lim Low, Linear least-squares optimization for point-to-plane ICP surface registration, Technical Report TR04-004, Department of Computer Science, University of North Carolina at Chapel Hill, 2004, The small-angle approximation of the rotation and the linear least squares problem in the six unknowns of the motion
  3. 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: the tangent plane method as a Gauss-Newton iteration with quadratic convergence for a zero-residual problem from a good start, and the linear convergence of ICP
  4. Szymon Rusinkiewicz and Marc Levoy, Efficient variants of the ICP algorithm, Proceedings of the Third International Conference on 3-D Digital Imaging and Modeling (3DIM), 2001, 145-152, The comparison of the point-to-point and point-to-plane error metrics on synthetic meshes, where point-to-plane converges in fewer iterations
  5. 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 point-to-point ICP that this method changes in the error metric

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