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.
- Solves
- Point cloud registration
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Aleksandr Segal, Dirk Haehnel, Sebastian Thrun, 2009
Generalized ICP (GICP) aligns a source point cloud to a target cloud like iterative closest point, but it gives every point a covariance that describes how sure its position is in each direction. With the pairs fixed, it chooses the motion that minimizes with , 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 with symmetric positive semidefinite covariances , target points with symmetric positive definite covariances , a start pose , an optional distance threshold , and a tolerance tol.
Output. A pose with at which the GICP cost of the current closest-point pairs is small. For a set of pairs the cost is
If is Gaussian with covariance and is Gaussian with covariance around positions that the true motion maps onto each other, then is Gaussian with mean 0 and covariance at the true motion. Minimizing maximizes the likelihood of the , 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 nearest neighbors, write it as with , and replace the eigenvalues by . The first column of is then the estimated normal (the principal component of least spread). The paper uses the 20 nearest neighbors and a small without a number; the reference code uses and .
The main loop holds the weights fixed during each fit. On the motion of the moved points , the residual changes to to first order, with , where is the skew matrix of the cross product.
GENERALIZED-ICP(A, B, C^A, C^B, R0, t0, d_max, tol)- 1
R ← R0 ; t ← t0 - 2
repeat (up to N iterations) - 3
Π ← {(i, j) : b_j closest to R a_i + t, and |R a_i + t - b_j| ≤ d_max} - 4
M_ij ← (C^B_j + R C^A_i Rᵀ)⁻¹ for (i, j) in Π ▷ held fixed below - 5
(R', t') ← minimize G with the weights M_ij fixed, from (R, t), by steps L6 and L7 - 6
solve H δ = -g, g = Σ J_iᵀ M_ij d_ij, H = Σ J_iᵀ M_ij J_i, δ = (w, u) - 7
λ ← 1 ; halve λ until G(Exp(λw) R, Exp(λw) t + λu) < G(R, t), then accept - 8
if |R' - R| + |t' - t| ≤ tol then (R, t) ← (R', t') and stop ; (R, t) ← (R', t') - 9
return R, t
Line L3 is the closest-point match of ICP, with the threshold of the paper that drops pairs farther than . 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 steps, until a step is tiny or no halved step lowers . The paper minimizes the cost with conjugate gradients and lets the weights change with 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 and .
Example
The target is a grid on the surface over , 144 points. The source is 70 of these points (seed 1), moved by the inverse of a rotation of 10 degrees about the axis and the translation . Both clouds get plane-to-plane covariances from their 10 nearest neighbors with . The start pose is the identity, and 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 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 and , 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 exists and is positive definite, because is positive definite and is positive semidefinite. Line L7 accepts only steps that lower , so the fixed-weight cost never rises in line L5, and every accepted rotation is proper. If is nonsingular and , the Gauss-Newton direction is a descent direction, so small enough steps lower . With and , is the point-to-point cost, whose minimum is the Kabsch solution. An exact rigid copy with the true pairs has 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 , 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 with covariances , and the target points are with covariances . All covariances are symmetric and positive semidefinite, and every is positive definite. In one iteration, line L3 gives a set of pairs , and line L4 gives the weights at the current rotation . For a pose let and
is the cost of line L5: pairs and weights fixed. The minimizer works on the motion applied to the current moved points , with , the gradient and the matrix . Line L6 solves , and line L7 tries the steps with and accepts the first one that lowers .
Claim.
- Each weight exists and is symmetric positive definite.
- Line L7 accepts a step only if it lowers , so never increases in line L5, and every accepted pose has .
- If is nonsingular and , then is a descent direction, and a small enough lowers .
- With and , is the point-to-point cost , whose minimum over is the Kabsch solution for the pairs.
- If the target is an exact rigid copy of the source and the pairs are the true ones, the true pose gives , which is the global minimum of .
Proof of 1. is symmetric positive semidefinite, since . Adding the positive definite gives a symmetric positive definite matrix, which is invertible, and its inverse is symmetric positive definite.
Proof of 2. Line L7 replaces the pose only when the new cost satisfies at the old pose. Each accepted rotation is , a product of two rotations.
Proof of 3. For the motion , , and . So changes to . Then , where the term depends on and the data. is a sum of matrices , which are positive semidefinite by part 1, so is positive semidefinite, and if it is nonsingular, it is positive definite. Then for . So for every small enough . 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 worse.
Proof of 4. With and , for every pair and every , so . 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 does not depend on , 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.
Proof of 5. If for every pair, then and . Each term of is a quadratic form of a positive definite matrix, so everywhere.
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 and 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.
What this proof does not give. The full GICP cost has weights that change with . 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 nearest neighbors of each point by sorting all distances, so the covariances cost ; each one then needs a eigendecomposition, . A k-d tree brings this to about on typical 3D data. In each outer iteration, line L3 costs by brute force, and line L4 inverts matrices of size , . Each inner step builds and in time, solves a system in , and evaluates at most 31 times in line L7, each. With at most inner steps, an outer iteration costs . The extra space holds the covariances and the weights, .
There is no bound on the number of outer iterations beyond the cap. Measured counts are benchmark results.
Properties
- Contains ICP. and 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 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 .
- 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
- in the covariances. Then is singular, and line L4 can fail when is also flat in the same direction. Keep .
- The wrong rotation of in line L4. The source covariance moves with the source points, so it is . Writing 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 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag W2QK6S Edit this page History Report an error Markdown