Algorithm Search⌘K

Algorithmadvanced

Generalized ICP

Also called GICP, plane-to-plane ICP.

ICP whose fit step weights each pair by the inverse of the summed covariances of both points, a maximum likelihood cost that contains point-to-point and, as a limit, point-to-plane ICP.

Time
O(n^2 log n + m^2 log m + N n (m + S)) worst · averageΘ(n^2 log n + m^2 log m + n m) best
Space
Θ(n + m) extra
Where
N = the number of outer iterations; S = the cap on inner Gauss-Newton steps; m = the number of target points; n = the number of source points
Properties
deterministicnot exactofflineiterative
Origin
Aleksandr Segal, Dirk Haehnel, Sebastian Thrun, 2009

Generalized ICP (GICP) aligns a source point cloud AA to a target cloud BB like iterative closest point, but it gives every point a 3×33 \times 3 covariance that describes how sure its position is in each direction. With the pairs fixed, it chooses the motion (R,t)(R, t) that minimizes ∑idiT(CjB+RCiART)−1di\sum_i d_i^{\mathsf T} (C^B_j + R C^A_i R^{\mathsf T})^{-1} d_i with di=bj−(Rai+t)d_i = b_j - (R a_i + t), which is the maximum likelihood motion when both points are Gaussian. With zero source covariances and identity target covariances this is point-to-point ICP, and with flat target covariances it tends to point-to-plane ICP. The usual plane-to-plane form makes every covariance flat: small along the surface normal of the point and large along its tangent plane, on both clouds. Like ICP, GICP is local and needs a good start.

In plain words

A laser point on a wall is known well in the direction across the wall, and poorly along the wall, because the wall looks the same there. GICP writes this as a small ellipsoid for every point: thin across the surface, wide along it.

When two points are paired, their ellipsoids are added. The gap between the points is then measured in units of this combined ellipsoid. A gap along both surfaces costs little. A gap across them costs a lot.

Every gap counts according to how sure both scans are. Plain ICP treats every direction the same. Point-to-plane ICP trusts only the target surface. GICP uses both surfaces, so the result does not depend much on which scan you call the source.

The problem

Input. Source points a1,…,ana_1, \ldots, a_n with symmetric positive semidefinite covariances CiAC^A_i, target points b1,…,bmb_1, \ldots, b_m with symmetric positive definite covariances CjBC^B_j, a start pose (R0,t0)(R_0, t_0), an optional distance threshold dmax⁡d_{\max}, and a tolerance tol.

Output. A pose (R,t)(R, t) with R∈SO(3)R \in SO(3) at which the GICP cost of the current closest-point pairs is small. For a set Π\Pi of pairs (i,j)(i, j) the cost is

G(R,t)=∑(i,j)∈ΠdijT(CjB+RCiART)−1dij,dij=bj−(Rai+t).G(R, t) = \sum_{(i, j) \in \Pi} d_{ij}^{\mathsf T} \big(C^B_j + R C^A_i R^{\mathsf T}\big)^{-1} d_{ij}, \qquad d_{ij} = b_j - (R a_i + t).

If aia_i is Gaussian with covariance CiAC^A_i and bjb_j is Gaussian with covariance CjBC^B_j around positions that the true motion maps onto each other, then dijd_{ij} is Gaussian with mean 0 and covariance CjB+RCiARTC^B_j + R C^A_i R^{\mathsf T} at the true motion. Minimizing GG maximizes the likelihood of the dijd_{ij}, with the normalizing factor of each Gaussian density taken as a constant, as in the paper.

The algorithm

The plane-to-plane covariances come first. For each point, take the covariance of its kk nearest neighbors, write it as Vdiag⁡(λ1,λ2,λ3)VTV \operatorname{diag}(\lambda_1, \lambda_2, \lambda_3) V^{\mathsf T} with λ1≤λ2≤λ3\lambda_1 \le \lambda_2 \le \lambda_3, and replace the eigenvalues by (ε,1,1)(\varepsilon, 1, 1). The first column of VV is then the estimated normal (the principal component of least spread). The paper uses the 20 nearest neighbors and a small ε\varepsilon without a number; the reference code uses k=10k = 10 and ε=10−3\varepsilon = 10^{-3}.

The main loop holds the weights fixed during each fit. On the motion x↦Exp⁡(w)x+ux \mapsto \operatorname{Exp}(w) x + u of the moved points xi=Rai+tx_i = R a_i + t, the residual changes to dij+Ji(w,u)d_{ij} + J_i (w, u) to first order, with Ji=[ [xi]×    −I ]J_i = [\,[x_i]_\times \;\; -I\,], where [x]×[x]_\times is the skew matrix of the cross product.

  1. GENERALIZED-ICP(A, B, C^A, C^B, R0, t0, d_max, tol)
  2. 1R ← R0 ; t ← t0
  3. 2repeat (up to N iterations)
  4. 3Π ← {(i, j) : b_j closest to R a_i + t, and |R a_i + t - b_j| ≤ d_max}
  5. 4M_ij ← (C^B_j + R C^A_i Rᵀ)⁻¹ for (i, j) in Π ▷ held fixed below
  6. 5(R', t') ← minimize G with the weights M_ij fixed, from (R, t), by steps L6 and L7
  7. 6solve H δ = -g, g = Σ J_iᵀ M_ij d_ij, H = Σ J_iᵀ M_ij J_i, δ = (w, u)
  8. 7λ ← 1 ; halve λ until G(Exp(λw) R, Exp(λw) t + λu) < G(R, t), then accept
  9. 8if |R' - R| + |t' - t| ≤ tol then (R, t) ← (R', t') and stop ; (R, t) ← (R', t')
  10. 9return R, t

Line L3 is the closest-point match of ICP, with the threshold of the paper that drops pairs farther than dmax⁡d_{\max}. Line L4 computes the weights from the rotation at the start of the iteration. Line L5 is the inner minimization: Gauss-Newton steps (line L6) with step halving (line L7), up to SS steps, until a step is tiny or no halved step lowers GG. The paper minimizes the cost with conjugate gradients and lets the weights change with RR during the minimization; the reference code freezes the weights in each outer iteration and uses Gauss-Newton, which gives a clean descent proof for the inner step. Line L8 measures the change of the pose by the sum of the absolute changes of the entries of RR and tt.

Example

The target is a 12×1212 \times 12 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, 144 points. The source is 70 of these points (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). Both clouds get plane-to-plane covariances from their 10 nearest neighbors with ε=10−3\varepsilon = 10^{-3}. The start pose is the identity, and dmax⁡d_{\max} is not used. Coordinates are unitless.

outer iteration GICP cost at the end of the iteration
1 1.3
2 0.129
3 3.2e-29
4 3.2e-29 (the pose no longer changes, stop)

The final rotation differs from the true one by 5×10−155 \times 10^{-15} radians. The whole run takes about 0.18 s in pure Python. On the same scene, point-to-point ICP needs 14 fit steps to reach the exact pose, and GICP with CA=0C^A = 0 and CB=IC^B = I, which is the same cost, needs 15 outer iterations. These counts are measurements on this one scene, not bounds.

Correctness

The proof in proofs/correctness.md shows five facts. Each weight MijM_{ij} exists and is positive definite, because CjBC^B_j is positive definite and RCiARTR C^A_i R^{\mathsf T} is positive semidefinite. Line L7 accepts only steps that lower GG, so the fixed-weight cost never rises in line L5, and every accepted rotation is proper. If HH is nonsingular and g≠0g \ne 0, the Gauss-Newton direction is a descent direction, so small enough steps lower GG. With CA=0C^A = 0 and CB=IC^B = I, GG is the point-to-point cost, whose minimum is the Kabsch solution. An exact rigid copy with the true pairs has G=0G = 0 at the true pose, the global minimum.

The proof does not show that the full cost falls from one outer iteration to the next: the weights change with RR, and the pairs change in line L3. The paper gives no convergence proof either.

Proof: The GICP step is well defined, never increases the fixed-weight cost, and contains point-to-point ICPfull

We use the notation of the page. The source points are a1,…,ana_1, \ldots, a_n with covariances CiAC^A_i, and the target points are b1,…,bmb_1, \ldots, b_m with covariances CjBC^B_j. All covariances are symmetric and positive semidefinite, and every CjBC^B_j is positive definite. In one iteration, line L3 gives a set Π\Pi of pairs (i,j)(i, j), and line L4 gives the weights Mij=(CjB+R0CiAR0T)−1M_{ij} = (C^B_j + R_0 C^A_i R_0^{\mathsf T})^{-1} at the current rotation R0R_0. For a pose (R,t)(R, t) let dij(R,t)=bj−(Rai+t)d_{ij}(R, t) = b_j - (R a_i + t) and

G(R,t)=∑(i,j)∈ΠdijTMij dij.G(R, t) = \sum_{(i, j) \in \Pi} d_{ij}^{\mathsf T} M_{ij}\, d_{ij} .

GG is the cost of line L5: pairs and weights fixed. The minimizer works on the motion x↦Exp⁡(w)x+ux \mapsto \operatorname{Exp}(w) x + u applied to the current moved points xi=Rai+tx_i = R a_i + t, with Ji=[ [xi]×    −I ]J_i = [\,[x_i]_\times \;\; -I\,], the gradient g=∑JiTMijdijg = \sum J_i^{\mathsf T} M_{ij} d_{ij} and the matrix H=∑JiTMijJiH = \sum J_i^{\mathsf T} M_{ij} J_i. Line L6 solves Hδ=−gH \delta = -g, and line L7 tries the steps λδ\lambda \delta with λ=1,1/2,1/4,…\lambda = 1, 1/2, 1/4, \ldots and accepts the first one that lowers GG.

Claim.

  1. Each weight MijM_{ij} exists and is symmetric positive definite.
  2. Line L7 accepts a step only if it lowers GG, so GG never increases in line L5, and every accepted pose has det⁡R=+1\det R = +1.
  3. If HH is nonsingular and g≠0g \ne 0, then δ\delta is a descent direction, and a small enough λ\lambda lowers GG.
  4. With CiA=0C^A_i = 0 and CjB=IC^B_j = I, GG is the point-to-point cost ∑∣Rai+t−bj∣2\sum |R a_i + t - b_j|^2, whose minimum over SO(3)×R3SO(3) \times \mathbb{R}^3 is the Kabsch solution for the pairs.
  5. If the target is an exact rigid copy of the source and the pairs are the true ones, the true pose gives G=0G = 0, which is the global minimum of GG.

Proof of 1. R0CiAR0TR_0 C^A_i R_0^{\mathsf T} is symmetric positive semidefinite, since vTR0CiAR0Tv=(R0Tv)TCiA(R0Tv)≥0v^{\mathsf T} R_0 C^A_i R_0^{\mathsf T} v = (R_0^{\mathsf T} v)^{\mathsf T} C^A_i (R_0^{\mathsf T} v) \ge 0. Adding the positive definite CjBC^B_j gives a symmetric positive definite matrix, which is invertible, and its inverse is symmetric positive definite. □\square

Proof of 2. Line L7 replaces the pose only when the new cost c2c_2 satisfies c2<Gc_2 < G at the old pose. Each accepted rotation is Exp⁡(λw)R\operatorname{Exp}(\lambda w) R, a product of two rotations. □\square

Proof of 3. For the motion x↦Exp⁡(w)x+ux \mapsto \operatorname{Exp}(w) x + u, Exp⁡(w)x=x+w×x+O(∣w∣2)\operatorname{Exp}(w) x = x + w \times x + O(|w|^2), and w×x=−x×w=−[x]×ww \times x = -x \times w = -[x]_\times w. So dijd_{ij} changes to dij+[xi]×w−u+O(∣w∣2)=dij+Ji(w,u)+O(∣w∣2)d_{ij} + [x_i]_\times w - u + O(|w|^2) = d_{ij} + J_i (w, u) + O(|w|^2). Then G(λδ)=G+2λ gTδ+O(λ2)G(\lambda \delta) = G + 2 \lambda\, g^{\mathsf T} \delta + O(\lambda^2), where the OO term depends on δ\delta and the data. HH is a sum of matrices JiTMijJiJ_i^{\mathsf T} M_{ij} J_i, which are positive semidefinite by part 1, so HH is positive semidefinite, and if it is nonsingular, it is positive definite. Then gTδ=−gTH−1g<0g^{\mathsf T} \delta = -g^{\mathsf T} H^{-1} g < 0 for g≠0g \ne 0. So G(λδ)<GG(\lambda \delta) < G for every small enough λ>0\lambda > 0. The code tries 30 halvings; with a finite cap, it may stop at a pose that is not stationary, but by part 2 it never makes GG worse. □\square

Proof of 4. With CiA=0C^A_i = 0 and CjB=IC^B_j = I, Mij=IM_{ij} = I for every pair and every R0R_0, so G(R,t)=∑∣bj−Rai−t∣2G(R, t) = \sum |b_j - R a_i - t|^2. This is the cost of the optimal superposition problem for the pairs, and the Kabsch algorithm with the sign fix gives its global minimum. In this case GG does not depend on R0R_0, so the outer loop of lines L2 to L8 alternates closest-point matching with a minimization of the ICP cost for the pairs, which is ICP whenever line L5 reaches the minimum. □\square

Proof of 5. If bj=R⋆ai+t⋆b_{j} = R^\star a_i + t^\star for every pair, then dij(R⋆,t⋆)=0d_{ij}(R^\star, t^\star) = 0 and G(R⋆,t⋆)=0G(R^\star, t^\star) = 0. Each term of GG is a quadratic form of a positive definite matrix, so G≥0G \ge 0 everywhere. □\square

Theorem. In each iteration, GENERALIZED-ICP builds positive definite weights, and its inner minimization returns a pose with a proper rotation and a fixed-weight cost no larger than at the start of the iteration; each accepted Gauss-Newton step strictly lowers that cost. With CA=0C^A = 0 and CB=IC^B = I the cost is that of point-to-point ICP, and an exact rigid copy has the true pose as a global minimizer of the fixed-pair cost.

Proof. Parts 1 to 5. ■\blacksquare

What this proof does not give. The full GICP cost ∑dT(CB+RCART)−1d\sum d^{\mathsf T} (C^B + R C^A R^{\mathsf T})^{-1} d has weights that change with RR. The code holds them fixed within an iteration, so the full cost at the end of an iteration is not proved to be lower than at the start, and a new match can raise it as well. Segal, Haehnel and Thrun (2009) minimize the full cost with conjugate gradients and give no convergence proof. The result is local, and it needs a good start.

Complexity

The model is the real RAM. The reference code finds the kk nearest neighbors of each point by sorting all distances, so the covariances cost Θ(n2log⁡n+m2log⁡m)\Theta(n^2 \log n + m^2 \log m); each one then needs a 3×33 \times 3 eigendecomposition, O(1)O(1). A k-d tree brings this to about (n+m)log⁡(n+m)(n + m) \log(n + m) on typical 3D data. In each outer iteration, line L3 costs Θ(nm)\Theta(n m) by brute force, and line L4 inverts nn matrices of size 3×33 \times 3, Θ(n)\Theta(n). Each inner step builds HH and gg in Θ(n)\Theta(n) time, solves a 6×66 \times 6 system in O(1)O(1), and evaluates GG at most 31 times in line L7, Θ(n)\Theta(n) each. With at most SS inner steps, an outer iteration costs O(nm+Sn)O(n m + S n). The extra space holds the covariances and the weights, Θ(n+m)\Theta(n + m).

There is no bound on the number NN of outer iterations beyond the cap. Measured counts are benchmark results.

Properties

  • Contains ICP. CA=0C^A = 0 and CB=IC^B = I give point-to-point ICP; flat target covariances give point-to-plane ICP in the limit.
  • Nearly symmetric. With plane-to-plane covariances on both clouds, swapping source and target changes the result little, unlike point-to-plane ICP, which uses the target normals only.
  • Monotone inside an iteration. The fixed-weight cost never rises in line L5. Across iterations, no monotone result is proved.
  • Local. The result depends on the start pose.
  • Robust to pairs that slide. A pair whose points lie on the same flat patch adds almost no cost for a slide along the patch, so wrong pairs on smooth surfaces hurt less.

Variants and improvements

  • Full weights in the minimizer. The paper keeps RCiARTR C^A_i R^{\mathsf T} inside the cost during the minimization and uses conjugate gradients; see the nonlinear conjugate gradient method.
  • Distributions instead of points. The normal distributions transform fits points to a grid of Gaussian cells, a related probabilistic cost without point pairs.
  • Voxelized GICP. Later work replaces the single closest target point by the Gaussian of a voxel, which removes most nearest neighbor queries.
  • Robust kernels. A Huber or Cauchy kernel on the Mahalanobis residual, as in an M-estimator, replaces the hard threshold dmax⁡d_{\max}.
  • Trimming. Keeping only the best fraction of pairs, as in trimmed ICP, handles partial overlap.

When to use it

Use GICP for laser or depth scans of scenes made of smooth surfaces, such as buildings, roads and rooms, when a rough pose is known. It is a good default when both clouds are dense enough for covariances, because it combines the speed of point-to-plane ICP with a symmetric use of both surfaces. Use plain ICP on sparse clouds where neighbors do not describe a surface. Use point-to-plane ICP when the target has good normals and the source is sparse. Without a rough pose, start with a global method.

Pitfalls

  • ε=0\varepsilon = 0 in the covariances. Then CjBC^B_j is singular, and line L4 can fail when CiAC^A_i is also flat in the same direction. Keep ε>0\varepsilon > 0.
  • The wrong rotation of CAC^A in line L4. The source covariance moves with the source points, so it is RCiARTR C^A_i R^{\mathsf T}. Writing RTCiARR^{\mathsf T} C^A_i R rotates it the wrong way and gives wrong weights for every turned pose.
  • No threshold in line L3. Points of the source with no partner in the target get a closest point anyway, and flat covariances do not remove their error across the surface. Set dmax⁡d_{\max} or trim.
  • Neighborhoods across edges. A neighborhood that crosses a corner gives a covariance that is not flat, and line L4 then treats the point as a blob. Use a neighborhood size that fits the sampling.
  • Expecting monotone outer costs. The cost recorded after line L5 in each outer iteration can rise from one iteration to the next, because the weights and pairs change. Do not stop on the first rise.

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()
generalized_icp.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-icp/. The authors are listed in prov/W2QK6S.jsonl.
"""Generalized-ICP (GICP) of Segal, Haehnel and Thrun.

Each source point a_i and target point b_j carries a 3 x 3 covariance
(C_i^A, C_j^B). With the matches fixed, the motion (R, t) minimizes

    sum_i d_i^T (C_j^B + R C_i^A R^T)^-1 d_i,   d_i = b_j - (R a_i + t),

which is the maximum likelihood estimate when both points are Gaussian.
C^A = 0 and C^B = I give point-to-point ICP. The plane-to-plane form takes
each covariance from the k nearest neighbors of the point, with the
eigenvalues replaced by (eps, 1, 1), so a point is sure along its normal
and unsure in its tangent plane.

Each iteration matches by Euclidean closest point (brute force,
Theta(n m)), drops pairs farther than d_max, computes the weights
M_i = (C_j^B + R C_i^A R^T)^-1 from the current R, and then minimizes
sum_i d_i^T M_i d_i over (R, t) with these weights held fixed, by
Gauss-Newton steps on the motion x -> Exp(w) x + u. A step is halved until
the cost goes down. The paper minimizes with conjugate gradients instead.
"""

from __future__ import annotations

from typing import List, Optional, Sequence, Tuple

from cvgeom import axis_angle_to_R
from cvla import add, inv, matvec, mul, skew, solve, sym_eig, transpose

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) -> Tuple[List[int], List[float]]:
    """Index of the closest target point of each point and the squared
    distance (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 plane_covariances(pts: Sequence[Sequence[float]], k: int = 10,
                      eps: float = 1e-3) -> List[Matrix]:
    """The plane-to-plane covariance of each point: the empirical covariance
    of its k nearest neighbors (itself included) is written V diag(w) V^T
    with w ascending, and w is replaced by (eps, 1, 1). The first column of
    V, the direction of least spread, is the estimated normal."""
    out = []
    for p in pts:
        d = sorted(range(len(pts)), key=lambda j: sum((pts[j][c] - p[c]) ** 2 for c in range(3)))
        nb = [pts[j] for j in d[:k]]
        mu = [sum(q[c] for q in nb) / len(nb) for c in range(3)]
        cov = [[sum((q[r] - mu[r]) * (q[c] - mu[c]) for q in nb) / len(nb) for c in range(3)] for r in range(3)]
        _, V = sym_eig(cov)
        D = [[eps, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
        out.append(mul(mul(V, D), transpose(V)))
    return out


def weights(R, CA, CB, pairs) -> List[Matrix]:
    """M = (C_j^B + R C_i^A R^T)^-1 for each pair (i, j)."""
    Rt = transpose(R)
    return [inv(add(CB[j], mul(mul(R, CA[i]), Rt))) for i, j in pairs]


def weighted_cost(R, t, A, B, pairs, Ms) -> float:
    """sum over the pairs of d^T M d, d = b_j - (R a_i + t)."""
    total = 0.0
    for (i, j), M in zip(pairs, Ms):
        x = [sum(R[r][c] * A[i][c] for c in range(3)) + t[r] for r in range(3)]
        d = [B[j][r] - x[r] for r in range(3)]
        total += sum(d[r] * sum(M[r][c] * d[c] for c in range(3)) for r in range(3))
    return total


def gicp_cost(R, t, A, B, CA, CB, pairs) -> float:
    """The GICP cost, with the weights taken at this R."""
    return weighted_cost(R, t, A, B, pairs, weights(R, CA, CB, pairs))


def minimize_fixed_weights(R, t, A, B, pairs, Ms, steps: int = 30,
                           tol: float = 1e-12) -> Tuple[Matrix, Vector]:
    """Gauss-Newton on (w, u) for fixed pairs and fixed weights, with step
    halving so that the cost never goes up. Stops when a step has norm at
    most tol, or when no halved step lowers the cost."""
    cost = weighted_cost(R, t, A, B, pairs, Ms)
    for _ in range(steps):
        H = [[0.0] * 6 for _ in range(6)]
        g = [0.0] * 6
        for (i, j), M in zip(pairs, Ms):
            x = [sum(R[r][c] * A[i][c] for c in range(3)) + t[r] for r in range(3)]
            d = [B[j][r] - x[r] for r in range(3)]
            S = skew(x)
            J = [S[r] + [-1.0 if c == r else 0.0 for c in range(3)] for r in range(3)]
            MJ = mul(M, J)
            Md = matvec(M, d)
            for a in range(6):
                g[a] += sum(J[r][a] * Md[r] for r in range(3))
                for b in range(6):
                    H[a][b] += sum(J[r][a] * MJ[r][b] for r in range(3))
        step = solve(H, [-v for v in g])  # @line L6
        if sum(v * v for v in step) <= tol * tol:
            break
        lam, moved = 1.0, False
        for _ in range(30):  # @line L7
            dR = axis_angle_to_R([lam * v for v in step[:3]])
            R2 = mul(dR, R)
            t2 = [a + lam * b for a, b in zip(matvec(dR, t), step[3:])]
            c2 = weighted_cost(R2, t2, A, B, pairs, Ms)
            if c2 < cost:
                R, t, cost, moved = R2, t2, c2, True
                break
            lam *= 0.5
        if not moved:
            break
    return R, t


def generalized_icp(A: Sequence[Sequence[float]], B: Sequence[Sequence[float]],
                    CA: Sequence[Matrix], CB: Sequence[Matrix],
                    R0: Optional[Sequence[Sequence[float]]] = None,
                    t0: Optional[Sequence[float]] = None,
                    max_iter: int = 30, d_max: Optional[float] = None,
                    tol: float = 1e-10) -> Tuple[Matrix, Vector, List[float]]:
    """GICP from the start pose (R0, t0) (default identity). Returns
    (R, t, costs), where costs[k] is the GICP cost at the end of iteration k
    (weights at the new R, same pairs). Stops when the motion changes by at
    most tol (sum of the absolute entry changes of R and t) or after
    max_iter iterations."""
    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
        idx, d2 = closest_points(transform(R, t, A), B)  # @line L3
        pairs = [(i, j) for i, (j, d) in enumerate(zip(idx, d2))  # @line L3
                 if d_max is None or d <= d_max * d_max]
        if len(pairs) < 3:
            raise ValueError("generalized_icp: fewer than 3 pairs within d_max")
        Ms = weights(R, CA, CB, pairs)  # @line L4
        R2, t2 = minimize_fixed_weights(R, t, A, B, pairs, Ms)  # @line L5
        costs.append(gicp_cost(R2, t2, A, B, CA, CB, pairs))
        change = sum(abs(R2[r][c] - R[r][c]) for r in range(3) for c in range(3)) + \
            sum(abs(a - b) for a, b in zip(t2, t))
        R, t = R2, t2
        if change <= tol:  # @line L8
            break  # @line L8
    return R, t, costs  # @line L9
test_generalized_icp.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-icp/. The authors are listed in prov/W2QK6S.jsonl.
import math
import random
import unittest

from cvgeom import add_noise, axis_angle_to_R, random_rotation
from cvla import det, matvec, mul, svd, transpose
from generalized_icp import (generalized_icp, minimize_fixed_weights,
                             plane_covariances, transform, weighted_cost,
                             weights)

TOL_ICP = 1e-6
ZERO = [[0.0] * 3 for _ in range(3)]
EYE = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]


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 kabsch(P, Y):
    """Reference closed form for point-to-point pairs, with the sign fix."""
    n = len(P)
    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 = [[sum((p[i] - pc[i]) * (y[j] - yc[j]) for p, y in zip(P, Y)) for j in range(3)] for i in range(3)]
    U, _, V = svd(H)
    d = 1.0 if det(mul(V, transpose(U))) >= 0 else -1.0
    R = mul(mul(V, [[1, 0, 0], [0, 1, 0], [0, 0, d]]), transpose(U))
    return R, [yc[i] - sum(R[i][k] * pc[k] for k in range(3)) for i in range(3)]


def surface_scene(k=12, n=70, seed=1):
    g = [-1.0 + 2.0 * i / (k - 1) for i in range(k)]
    B = [[x, y, 0.3 * math.sin(2 * x) * math.cos(1.5 * y) + 0.1 * x * x] for x in g for y in g]
    rng = random.Random(seed)
    sel = rng.sample(range(len(B)), n)
    R = axis_angle_to_R([1.0, 2.0, 3.0], math.radians(10.0))
    t = [0.05, -0.03, 0.04]
    Rt = transpose(R)
    A = [[sum(Rt[i][c] * (B[j][c] - t[c]) for c in range(3)) for i in range(3)] for j in sel]
    return A, B, R, t


class TestGeneralizedICP(unittest.TestCase):
    def test_plane_to_plane_exact_recovery(self):
        A, B, R, t = surface_scene()
        Rf, tf, costs = generalized_icp(A, B, plane_covariances(A), plane_covariances(B))
        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_point_to_point_case_matches_kabsch(self):
        # C^A = 0 and C^B = I: the fixed-pair minimum is the Kabsch solution.
        rng = random.Random(2)
        A = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(15)]
        B = add_noise(rng, transform(axis_angle_to_R([0, 0, 1], 0.4), [0.2, -0.1, 0.0], A), 0.05)
        pairs = [(i, i) for i in range(len(A))]
        Ms = weights(EYE, [ZERO] * 15, [EYE] * 15, pairs)
        R, t = minimize_fixed_weights(EYE, [0.0, 0.0, 0.0], A, B, pairs, Ms)
        Rk, tk = kabsch(A, B)
        self.assertLess(rot_angle(R, Rk), 1e-8)
        self.assertLess(max(abs(a - b) for a, b in zip(t, tk)), 1e-8)

    def test_fixed_pair_minimum_against_random_motions(self):
        # Brute force: no random small change of the result has a lower cost.
        A, B, _, _ = surface_scene(k=8, n=25, seed=3)
        rng = random.Random(3)
        B = add_noise(rng, B, 0.01)
        CA, CB = plane_covariances(A, k=8), plane_covariances(B, k=8)
        pairs = [(i, i) for i in range(10)]
        Bp = [B[i] for i in range(10)]
        CBp = [CB[i] for i in range(10)]
        Ms = weights(axis_angle_to_R([0.0, 0.0, 0.1]), CA, CBp, pairs)
        R, t = minimize_fixed_weights(EYE, [0.0, 0.0, 0.0], A, Bp, pairs, Ms, steps=50)
        best = weighted_cost(R, t, A, Bp, pairs, Ms)
        for _ in range(200):
            dR = axis_angle_to_R([rng.gauss(0, 1e-3) for _ in range(3)])
            R2 = mul(dR, R)
            t2 = [v + rng.gauss(0, 1e-3) for v in t]
            self.assertGreaterEqual(weighted_cost(R2, t2, A, Bp, pairs, Ms), best - 1e-12)

    def test_plane_covariance_shape(self):
        rng = random.Random(4)
        R = random_rotation(rng)
        pts = transform(R, [0.0, 0.0, 0.0], [[rng.uniform(-1, 1), rng.uniform(-1, 1), 0.0] for _ in range(30)])
        normal = [R[0][2], R[1][2], R[2][2]]
        tangent = [R[0][0], R[1][0], R[2][0]]
        for C in plane_covariances(pts, k=8, eps=1e-3):
            cn, ct = matvec(C, normal), matvec(C, tangent)
            for c in range(3):
                self.assertAlmostEqual(cn[c], 1e-3 * normal[c], places=9)
                self.assertAlmostEqual(ct[c], tangent[c], places=9)

    def test_d_max_too_small(self):
        A, B, _, _ = surface_scene(k=6, n=10)
        with self.assertRaises(ValueError):
            generalized_icp(A, B, [ZERO] * len(A), [EYE] * len(B), d_max=1e-6)


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

History

Segal, Haehnel and Thrun presented Generalized-ICP at Robotics: Science and Systems in 2009. They wrote the fit step of ICP as a maximum likelihood problem with a covariance on each point, showed that point-to-point and point-to-plane ICP are special cases, and proposed the plane-to-plane model with covariances from local neighborhoods. Their experiments on simulated and real laser data showed fewer failures than point-to-point and point-to-plane ICP over a range of start poses and thresholds, which are benchmark results. GICP became a standard registration method in laser mapping and is included in common point cloud libraries.

References

  1. Aleksandr Segal, Dirk Haehnel and Sebastian Thrun, Generalized-ICP, Robotics: Science and Systems V (RSS 2009), The probabilistic derivation of the cost (Eq. 2), its point-to-point and point-to-plane special cases, the plane-to-plane covariances from the 20 nearest neighbors with a small variance along the normal, the distance threshold d_max, and the minimization by conjugate gradients
  2. Paul J. Besl and Neil D. McKay, A method for registration of 3-D shapes, IEEE Transactions on Pattern Analysis and Machine Intelligence 14(2), 1992, 239-256, The point-to-point ICP that GICP contains as the case of zero source covariance and identity target covariance
  3. Yang Chen and Gérard Medioni, Object modelling by registration of multiple range images, Image and Vision Computing 10(3), 1992, 145-155, The point-to-plane error that GICP contains as a limit case
  4. Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 10, Least-squares problems (the Gauss-Newton method), and Chapter 3, Line search methods (backtracking)

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