Algorithmresearch
Go-ICP
Also called globally optimal ICP.
Finds the rigid motion that minimizes the ICP cost over a whole box of rotations and translations, within a gap eps, by nested branch and bound with local ICP for upper bounds.
- Solves
- Point cloud registration
- Time
- O(K T n m) worst · averageΘ(n m) best
- Space
- O(K + T + n) extra
- Where
- K = the number of rotation cubes examined; T = the largest number of translation cubes examined for one rotation cube; 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
- Jiaolong Yang, Hongdong Li, Yunde Jia, Dylan Campbell, 2013
Go-ICP finds the rigid motion that best aligns a source point cloud to a target under the cost of iterative closest point, the sum of squared closest-point distances, over a whole box of rotations and translations, not only near a start pose. It searches the rotations, written as angle-axis vectors in a cube, by best-first branch and bound. For each rotation cube, an inner branch and bound over the translations gives a lower bound of the cost on the cube. Local ICP, started from the best poses that the search finds, gives upper bounds. The search stops when the best cost found is within of the least lower bound, so the result is within of the global minimum over the box. The bounds come from two inequalities of Yang, Li, Campbell and Jia: how far a point can move when the rotation varies in a cube, and how much each residual can change. The price is time: the search can examine many thousands of cubes.
In plain words
Plain ICP walks downhill from where it starts and stops in the first valley. Go-ICP looks at every possible turn and slide, but in a clever way.
It splits the space of all turns into boxes. For a box, it asks: what is the best cost that any turn in this box could possibly reach? A short calculation gives a number that is sure to be at most that cost. If this number is already worse than the best answer found so far, the whole box is dropped. Otherwise the box is split into eight smaller boxes, and the question is asked again.
To find good answers early, it runs plain ICP from promising places. The search ends when no box left could beat the best answer by more than a small margin .
The problem
Input. A source and a target in , a cube of angle-axis vectors (by default ), a cube of translations, and a gap . Coordinates are unitless in the tests.
Output. A pose with and its cost , where
such that , with the least cost over the rotations , with , and the translations . Here is the rotation by the angle about the axis (see the axis-angle representation); the ball holds every rotation.
The algorithm
The bounds rest on two facts. Let lie in a rotation cube of half side with center , and in a translation cube of half side with center .
- Rotation uncertainty (Theorem 1 of the paper): . The angle between and is at most , a lemma that goes back to Hartley and Kahl (2009), and the chord of that angle is the bound.
- Residual bound (Theorem 2 of the paper): with , , by the triangle inequality.
For a rotation cube with center , the inner search minimizes with . Since on the cube, a lower bound of over is a lower bound of over the cube.
GO-ICP(P, Q, ε, C_r, C_t)- 1
(R, t, E) ← LOCAL-ICP(P, Q) from the start pose ; queue ← {(0, C_r)} - 2
while the queue is not empty and E - (least bound in the queue) ≥ ε - 3
pop the cube of least bound ; h ← its half side / 2 ; γ_i ← 2 sin(min(√3 h / 2, π/2)) |p_i| - 4
for each of its 8 sub-cubes, with center r0 and half side h, skipping those with |r0| - √3 h > π - 5
(E_t, t_b, L) ← INNER-BNB(R_r0 P, γ, Q, C_t, E, ε/2, ε) - 6
if t_b ≠ none and E(R_r0, t_b) < E then update (R, t, E), then run LOCAL-ICP from (R_r0, t_b) and keep it if better - 7
if L < E then push (L, sub-cube) - 8
return R, t, E INNER-BNB(X, γ, Q, C_t, E_b, δ, enough) ▷ X = R_r0 P ; f(t) = Σ max(e_i(t) - γ_i, 0)²- 9
E_t ← E_b ; t_b ← none ; try the center of C_t ; push C_t with its bound if the bound < E_t - 10
while the queue is not empty and E_t - lb ≥ δ and E_b - lb ≥ enough ▷ lb = least bound - 11
pop the cube of least bound ; s ← its half side / 2 ; γ_t ← √3 s ; for each of its 8 sub-cubes, center c: - 12
if f(c) < E_t then E_t ← f(c) ; t_b ← c - 13
f_low ← Σ max(e_i(c) - γ_i - γ_t, 0)² ; if f_low < E_t then push (f_low, sub-cube) - 14
return E_t, t_b, L = min(E_t, least bound in the queue)
The outer search (lines L1 to L8) keeps the best cost and a queue of rotation cubes ordered by their lower bounds. Line L3 splits the cube of least bound. Line L4 drops sub-cubes that lie wholly outside the ball of radius , since they hold no new rotation. Line L5 runs the inner search over translations with the rotation uncertainties of the sub-cube. Line L6 evaluates the true cost at the center rotation and the best translation of the inner search. If it beats , it becomes the new , and a local ICP from there often lowers at once. Line L7 keeps the sub-cube only if its bound can still beat .
The inner search (lines L9 to L14) is the same idea over translations. It stops when its best value is within of its least bound, or when its least bound is within of the outer , which is enough for the outer test. It returns a true lower bound of over .
The reference code differs from the paper in three ways. First, the paper runs a second inner search with for the upper bound; the code reads the upper bound off the lower-bound search in line L6, which keeps the guarantee, as the proof shows, and costs much less. Second, the inner search returns a certified lower bound and uses the two stop rules of line L10. Third, closest points are found by brute force, per evaluation; the paper looks them up in a precomputed 3D distance transform, which makes each lookup but adds the error of the grid.
Example
The target is 20 points drawn uniformly in (seed 5). The source is 10 of them, moved by the inverse of a rotation of 150 degrees about the axis and the translation , without noise. So the true cost is 0.
- Local ICP from the identity stops at the cost 0.7042, a wrong pose.
- Go-ICP over , and returns the cost and the true pose to within . It examines 217 rotation cubes and runs local ICP 3 times, in about 0.36 s of pure Python.
Noise makes the certificate expensive. With 6 source points out of 10 target points and Gaussian noise of standard deviation 0.03 on each coordinate, the minimum is above , so the bounds must prune instead of stopping at a zero cost. Over a rotation cube of half side 0.3 that holds the true rotation, with and , Go-ICP returns the cost 0.015472 after 248 rotation cubes and one local ICP, in about 0.74 s. The test checks it against 61 runs of local ICP from random rotations and from the true one: none of them is lower by or more. Over the full cube with , the same scene takes 3980 rotation cubes and about 27 s. These times are measurements of the reference code on one machine.
Correctness
Claim: Go-ICP stops, and returns with , and . The invariant is: every pose of the domain has its rotation in a cube of the queue, or has a cost of at least the current . Cubes leave the queue only by a split, by line L4 (no rotation of the ball), or by line L7 (a bound of at least , which stays valid because only falls). The bounds are valid by the two facts above. So when the least bound in the queue is above , so is . Termination holds because the gap between the true cost and the bound of a cube of half side shrinks in proportion to , so small cubes either are dropped or end the search when they reach the top of the queue. The full proof, with a proof of the rotation uncertainty bound, is in proofs/correctness.md.
Proof: Go-ICP returns a pose within eps of the global minimum over its domain, and stopsfull
We use the notation of the page. The source is and the target is in . For an angle-axis vector , is the rotation by the angle about . The residuals and the cost are
The rotation domain is a cube of angle-axis vectors, and the translation domain is a cube with center and half side . A cube of half side is the set of points whose coordinates differ from those of its center by at most , so every point of it is within of the center. Let and ; the minimum exists because is compact and is continuous. We assume exact arithmetic and eps .
Claim. GO-ICP stops after finitely many steps and returns with , and .
Lemma 1 (rotation uncertainty). Let lie in a cube of half side with center . Then for every ,
Proof. Let for and . The derivative of has the form with , where for
is the left Jacobian of the exponential map of , and . maps to , since . For a unit vector orthogonal to , with and , we get and , so . This vector is orthogonal to , and its length is . So maps the line of and the plane orthogonal to it into themselves, it is the identity on the line, and it multiplies lengths in the plane by . Write as the sum of its parts on the line and in the plane; the images of the parts are orthogonal, so for all . Hence .
The point stays on the sphere of radius about the origin, and . So the length of the path is at most . The angle between and times is the length of the shortest path on the sphere between them, so . Also . The chord is , and increases on , so the chord is at most .
Lemma 2 (residual bound). Let lie in the rotation cube of half side with center , and in the translation cube of half side with center . Let and . Then and .
Proof. For every , the triangle inequality and Lemma 1 give . Take the minimum over , and use . The second bound is the case , .
Fix a rotation cube with center and half side , and let . Define . Squaring keeps the order of nonnegative numbers, so Lemma 2 gives for every in the cube, and, for a translation cube of half side and center , for every in it.
Lemma 3 (the inner search). INNER-BNB, called with the bound , returns such that: ; if is not None, and ; and . It stops after finitely many steps.
Proof. The value starts at (line L9) and changes only to a value at an evaluated center with (line L12), and then . Centers of sub-cubes of lie in . This gives the first two parts.
For the third part, say that a cube was not pushed when its bound was at least the value of at the time it was made. Invariant: every lies in a cube in the queue, or in a cube that was not pushed. This holds at the start, because is pushed or not pushed in line L9, and a popped cube is the union of its 8 children, each pushed or not pushed in line L13. If lies in a cube that was not pushed, then , since never increases. If lies in a cube in the queue, is at least the bound of that cube, and so at least the least bound in the queue. Line L14 returns , or if the queue is empty, so for every , and .
Termination. Let bound over and all ; it exists since is bounded. For and , . So for a cube of half side and center , . When a cube is pushed, already holds (line L12 runs before line L13), and never increases. So when a cube of half side is at the top of the queue, . Once this is below , and line L10 stops. There are cubes of half side , so only finitely many cubes of half side at least that threshold can be popped. Hence the search stops.
Lemma 4 (the outer lower bound). When line L7 pushes a rotation cube with center and half side and bound , then for every in that cube and .
Proof. by the remark after Lemma 2 and Lemma 3.
Proof of the claim: the returned value. is set in line L1 to the cost of the pose that local ICP returns, and later only to , computed from the true residuals, or to the cost that local ICP returns, which it computes at the pose it returns. So at the end. Every rotation is , the identity, or a Kabsch rotation with the sign fix, so .
Proof of the claim: the bound. Invariant of the outer loop: every has in a rotation cube in the queue, or for the current . At the start the queue holds with the bound 0, which is a valid lower bound. When a cube is popped, its 8 children cover it. A child that line L4 drops has , so every in it has , and it holds no point of . A child that line L7 does not push has at that time, so by Lemma 4 every with in it has ; and never increases later. A child that is pushed is in the queue, with a valid bound by Lemma 4. So the invariant holds. At the stop, either the queue is empty and , or the least bound lb in the queue has , and . In both cases .
Proof of the claim: termination. Each call of INNER-BNB stops by Lemma 3; it uses and the extra stop rule with the current . Let bound all residuals over all rotations and . For a rotation cube of half side , , and so for every , , by the inequality of Lemma 3 with . Consider a child cube whose inner search, called with equal to the current , returns with , or if the queue is empty. The search ends in one of three ways. If the queue is empty, . If it breaks because , then . If it breaks because , then or . So either (i) , or (ii) .
In case (i), the cube is pushed only if , and then . In case (ii) with not None, line L6 leaves . In case (ii) with None, , so . So once , a child of half side is either not pushed, or pushed with for the of that moment. Later values of are not larger, so the gap stays below eps. When such a cube reaches the top of the queue, line L2 stops. Only finitely many cubes have , since there are cubes at depth and as . Each pop takes finitely many steps. Hence GO-ICP stops.
Remarks. The returned pose need not lie in , because the local ICP of line L6 can move outside the domain; the bound compares with the least cost over , and a pose outside with a smaller cost only helps. In floating point the bounds are computed with rounding, so the guarantee holds up to the rounding error of the sums. The upper bound of line L6 replaces the second inner search of Yang et al. with ; the proof above shows that the guarantee does not need that search.
Complexity
The model is the real RAM. Each evaluation of the residuals at one pose costs by brute force. The inner search for one rotation cube evaluates 8 sub-cubes per pop, so it costs if it examines at most translation cubes. The outer search examines rotation cubes, and each one costs one inner search, so the total is plus the local ICP runs, which cost per ICP iteration. With a distance transform, each evaluation costs after the preprocessing of a grid.
and are not polynomial in the input in the worst case. A cube must shrink until the gap between its bound and the cost is below about , which needs a half side proportional to , and there are about cubes of half side in a fixed box. So the worst case grows like for each of the two searches. In practice, local ICP finds a near-optimal cost early, and most cubes are dropped at large sizes. The counts in the example are benchmark results, not bounds. The space holds the two queues and the residuals, .
Properties
- Global within . The result is within of the least cost over the domain, as a proved bound, not a measured rate.
- A certificate. The least bound in the queue at the stop is a lower bound of the optimal cost.
- Deterministic. The same input gives the same output.
- Slow in the worst case. The running time grows quickly as falls and as noise lifts the optimal cost above zero.
- Sensitive to outliers in the plain form. The plain cost sums all residuals, so points without partners lift the optimum; the trimmed form handles them.
Variants and improvements
- Trimming. The paper extends the bounds to a trimmed cost that keeps a fixed fraction of the smallest residuals, as in trimmed ICP.
- Distance transform. A precomputed 3D distance transform of the target replaces the nearest neighbor search by a table lookup.
- Better bounds. Later work tightens the rotation bounds or searches rotations and translations jointly, which prunes more cubes.
- Other global methods. TEASER certifies a robust pose from feature matches. Fast global registration and 4PCS are fast, but they give no certificate of the optimum.
When to use it
Use Go-ICP when no start pose is known, the clouds are small (hundreds to a few thousand points), and a proof of near-optimality matters, for example to check other methods or in safety reviews. For large clouds or when time is short, get a rough pose by feature matching with RANSAC or by a fast global method, then refine it with ICP. If the clouds overlap only in part, use the trimmed cost. Limit the rotation and translation domains when prior knowledge allows: the example shows that a small rotation cube is much cheaper than the full one.
Pitfalls
- A translation box that is too small in line L5. The guarantee holds only over . If the true translation lies outside it, Go-ICP returns the best pose inside, which can be wrong. Center the clouds and choose large enough.
- The rotation bound without the min in line L3. Using for large cubes is valid but loose; using without the min is wrong when , because the sine then falls. Use .
- A best value in place of a lower bound in line L14. If the inner search returns its best value instead of , the outer bound is not valid, and the search can drop the cube that holds the optimum.
- Too small an in line L2. With noise, a tiny gap makes the search split cubes until rounding error, and the time explodes. Choose on the scale of the noise times the number of points.
- Uncentered clouds. The rotation bound grows with . Center at its centroid first, so that the bounds are tight.
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()
go_icp.py 214 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/go-icp/. The authors are listed in prov/AT1CTF.jsonl.
"""Go-ICP of Yang, Li, Campbell and Jia: globally optimal ICP by nested
branch and bound.
The cost is E(R, t) = sum_i e_i^2, with e_i = min_j ||R p_i + t - q_j||.
Rotations are angle-axis vectors r in a cube (by default [-pi, pi]^3, which
holds the pi-ball of all rotations). Translations are in a cube given by
its center and half side.
For a rotation cube of half side sigma_r with center r0, and a translation
cube of half side sigma_t with center t0, every (r, t) in the two cubes has
e_i(R_r, t) >= max(e_i(R_r0, t0) - gamma_ri - gamma_t, 0),
gamma_ri = 2 sin(min(sqrt(3) sigma_r / 2, pi / 2)) ||p_i||,
gamma_t = sqrt(3) sigma_t.
The outer search splits rotation cubes, best first. For each cube it runs
an inner search over translation with the gamma_r of the cube, which
gives a lower bound for the whole cube. The true cost at the center
rotation and the best translation of that search is an upper bound; if it
beats the best cost E*, a local ICP starts there, which often lowers E* at
once. The search stops when E* minus the least lower bound in the queue is
below eps, so E* is within eps of the global minimum over the domain.
Three choices differ from the paper. The paper runs a second inner search
with gamma_r = 0 for the upper bound; here the upper bound is read off the
lower-bound search, which keeps the guarantee and costs much less. The
inner search returns a true lower bound (the least of its best value and
the bounds left in its queue). It stops when that bound is within eps / 2
of its best value, or within eps of E*, so the outer stop rule is always
reached and no work is spent past it. Closest points are found by brute force,
Theta(n m) per evaluation; the paper uses a distance transform.
"""
from __future__ import annotations
import heapq
import itertools
import math
from typing import Dict, List, Optional, Sequence, Tuple
from cvgeom import axis_angle_to_R
from cvla import det, mul, svd, transpose
Matrix = List[List[float]]
Vector = List[float]
SQRT3 = math.sqrt(3.0)
_SIGNS = [(a, b, c) for a in (-1.0, 1.0) for b in (-1.0, 1.0) for c in (-1.0, 1.0)]
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 residuals(moved, t, Q) -> List[float]:
"""e_i = distance from moved[i] + t to its closest point of Q (brute force)."""
out = []
tx, ty, tz = t
for x, y, z in moved:
x, y, z = x + tx, y + ty, z + tz
best = min((x - a) * (x - a) + (y - b) * (y - b) + (z - c) * (z - c) for a, b, c in Q)
out.append(math.sqrt(best))
return out
def cost(R, t, P, Q) -> float:
"""E(R, t) = sum of squared closest-point distances."""
return sum(e * e for e in residuals(transform(R, [0.0, 0.0, 0.0], P), t, Q))
def rotation_uncertainty(norm_p: float, sigma_r: float) -> float:
"""gamma_r of Theorem 1: a bound on ||R_r p - R_r0 p|| for every r in the
cube of half side sigma_r around r0."""
return 2.0 * math.sin(min(SQRT3 * sigma_r / 2.0, math.pi / 2.0)) * norm_p
def _closest_index(pts, Q) -> List[int]:
idx = []
for x, y, z in pts:
best, bj = float("inf"), -1
for j, (a, b, c) in enumerate(Q):
d = (x - a) * (x - a) + (y - b) * (y - b) + (z - c) * (z - c)
if d < best:
best, bj = d, j
idx.append(bj)
return idx
def _kabsch(P, Y) -> Tuple[Matrix, Vector]:
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, 0.0], [0.0, 1.0, 0.0], [0.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 local_icp(P, Q, R, t, max_iter: int = 50) -> Tuple[Matrix, Vector, float]:
"""Point-to-point ICP from (R, t). Returns (R, t, E) with E the cost at
the returned pose. The cost never goes up."""
R, t = [list(r) for r in R], list(t)
E = cost(R, t, P, Q)
prev = None
for _ in range(max_iter):
idx = _closest_index(transform(R, t, P), Q)
if idx == prev:
break
R2, t2 = _kabsch(P, [Q[j] for j in idx])
E2 = cost(R2, t2, P, Q)
if E2 >= E:
break
R, t, E, prev = R2, t2, E2, idx
return R, t, E
def inner_bnb(moved, gammas, Q, t_center, t_half, E_bound, delta, enough=0.0):
"""Branch and bound over the translation cube for one rotation.
moved holds R_r0 p_i, and gammas the rotation uncertainties gamma_ri
(zeros to minimize the cost itself). The function to minimize is
f(t) = sum_i max(e_i(R_r0, t) - gamma_ri, 0)^2. The search stops when
the least bound in the queue is within delta of the best value found, or
within enough of E_bound. Returns (E_t, t_best, L):
E_t = min(E_bound, least f found), t_best its translation (None if no
value below E_bound was found), and L <= min over the cube of f."""
Et, tbest = E_bound, None # @line L9
e = residuals(moved, t_center, Q)
up = sum(max(a - g, 0.0) ** 2 for a, g in zip(e, gammas))
if up < Et:
Et, tbest = up, list(t_center)
gt = SQRT3 * t_half
lb = sum(max(a - g - gt, 0.0) ** 2 for a, g in zip(e, gammas))
count = itertools.count()
heap = [(lb, next(count), list(t_center), t_half)] if lb < Et else [] # @line L9
while heap: # @line L10
lb, _, c, s = heap[0]
if Et - lb < delta or E_bound - lb < enough: # @line L10
break
heapq.heappop(heap)
h = s / 2.0 # @line L11
gt = SQRT3 * h # @line L11
for sx, sy, sz in _SIGNS: # @line L11
c2 = [c[0] + sx * h, c[1] + sy * h, c[2] + sz * h]
e = residuals(moved, c2, Q)
up = sum(max(a - g, 0.0) ** 2 for a, g in zip(e, gammas)) # @line L12
if up < Et: # @line L12
Et, tbest = up, c2
low = sum(max(a - g - gt, 0.0) ** 2 for a, g in zip(e, gammas)) # @line L13
if low < Et: # @line L13
heapq.heappush(heap, (low, next(count), c2, h))
L = min(Et, heap[0][0]) if heap else Et # @line L14
return Et, tbest, L # @line L14
def go_icp(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]], eps: float,
t_center: Sequence[float] = (0.0, 0.0, 0.0), t_half: float = 1.0,
r_center: Sequence[float] = (0.0, 0.0, 0.0), r_half: float = math.pi,
R0: Optional[Sequence[Sequence[float]]] = None,
t0: Optional[Sequence[float]] = None,
stats: Optional[Dict[str, int]] = None) -> Tuple[Matrix, Vector, float]:
"""Globally optimal registration of P to Q by nested branch and bound.
The rotation domain is the cube of angle-axis vectors with center
r_center and half side r_half; the translation domain is the cube with
center t_center and half side t_half. Sub-cubes that lie wholly outside
the ball of radius pi are dropped, since that ball already holds every
rotation. Returns (R, t, E) with E = cost(R, t, P, Q) and E <= m + eps,
where m is the least cost over the domain poses whose angle-axis vector
has norm at most pi.
If stats is a dict, it receives the number of rotation cubes looked at
and the number of local ICP runs."""
if eps <= 0:
raise ValueError("go_icp: eps must be positive")
eye = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
R, t, E = local_icp(P, Q, R0 if R0 is not None else eye, # @line L1
t0 if t0 is not None else [0.0, 0.0, 0.0])
norms = [math.sqrt(sum(v * v for v in p)) for p in P]
count = itertools.count()
heap = [(0.0, next(count), list(r_center), r_half)] # @line L1
cubes = icp_runs = 0
while heap: # @line L2
lb, _, c, s = heap[0]
if E - lb < eps: # @line L2
break
heapq.heappop(heap)
h = s / 2.0 # @line L3
gammas = [rotation_uncertainty(n, h) for n in norms] # @line L3
for sx, sy, sz in _SIGNS: # @line L4
r0 = [c[0] + sx * h, c[1] + sy * h, c[2] + sz * h]
if math.sqrt(sum(v * v for v in r0)) - SQRT3 * h > math.pi: # @line L4
continue
cubes += 1
Rr = axis_angle_to_R(r0)
moved = transform(Rr, [0.0, 0.0, 0.0], P)
_, tb, low = inner_bnb(moved, gammas, Q, t_center, t_half, E, eps / 2.0, eps) # @line L5
if tb is not None:
Eu = sum(e * e for e in residuals(moved, tb, Q)) # @line L6
if Eu < E: # @line L6
R, t, E = Rr, tb, Eu
icp_runs += 1
R2, t2, E2 = local_icp(P, Q, Rr, tb) # @line L6
if E2 < E:
R, t, E = R2, t2, E2
if low < E: # @line L7
heapq.heappush(heap, (low, next(count), r0, h)) # @line L7
if stats is not None:
stats["rotation_cubes"] = cubes
stats["icp_runs"] = icp_runs
return R, t, E # @line L8
test_go_icp.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/go-icp/. The authors are listed in prov/AT1CTF.jsonl.
import math
import random
import unittest
from cvgeom import axis_angle_to_R, random_rotation
from cvla import det, mul, transpose
from go_icp import (cost, go_icp, inner_bnb, local_icp, residuals,
rotation_uncertainty, transform)
EYE = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
ZERO3 = [0.0, 0.0, 0.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 scene(n, m, seed, noise=0.0):
"""m target points in [-0.6, 0.6]^3. The source is n of them, moved by
the inverse of a 150 degree rotation and a translation, plus noise.
Returns (P, Q, R, t, r) with r the angle-axis vector of R."""
rng = random.Random(seed)
Q = [[rng.uniform(-0.6, 0.6) for _ in range(3)] for _ in range(m)]
sel = rng.sample(range(m), n)
axis = [1.0, -1.0, 2.0]
angle = math.radians(150.0)
R = axis_angle_to_R(axis, angle)
t = [0.1, -0.05, 0.08]
P = [[sum(R[k][i] * (Q[s][k] - t[k]) for k in range(3)) + rng.gauss(0.0, noise) for i in range(3)]
for s in sel]
na = math.sqrt(sum(a * a for a in axis))
return P, Q, R, t, [angle * a / na for a in axis]
class TestGoICP(unittest.TestCase):
def test_global_where_icp_fails(self):
P, Q, R, t, _ = scene(10, 20, 5)
self.assertGreater(local_icp(P, Q, EYE, ZERO3)[2], 0.1)
Rg, tg, E = go_icp(P, Q, 0.01, t_half=0.5)
self.assertLess(E, 1e-12)
self.assertLess(rot_angle(R, Rg), 1e-6)
self.assertLess(max(abs(a - b) for a, b in zip(t, tg)), 1e-6)
self.assertAlmostEqual(det(Rg), 1.0, places=12)
self.assertAlmostEqual(cost(Rg, tg, P, Q), E, places=12)
def test_eps_optimal_against_many_icp_starts(self):
# Noisy data, so the optimum is above eps and the bounds must prune.
P, Q, _, _, r = scene(6, 10, 5, noise=0.03)
eps = 0.014
rc = [r[0] + 0.2, r[1] - 0.1, r[2] + 0.15]
Rg, tg, E = go_icp(P, Q, eps, t_half=0.2, r_center=rc, r_half=0.3)
self.assertGreater(E, eps)
rng = random.Random(8)
starts = [random_rotation(rng) for _ in range(60)] + [axis_angle_to_R(r)]
best = min(local_icp(P, Q, R0, ZERO3)[2] for R0 in starts)
self.assertLessEqual(E, best + eps)
self.assertGreaterEqual(best, E - eps)
self.assertAlmostEqual(cost(Rg, tg, P, Q), E, places=12)
def test_rotation_uncertainty(self):
# Theorem 1: ||R_r x - R_r0 x|| <= gamma_r for r in the cube.
rng = random.Random(3)
for _ in range(400):
sigma = rng.choice([0.05, 0.3, 1.0, 2.0])
r0 = [rng.uniform(-2.0, 2.0) for _ in range(3)]
r = [c + rng.uniform(-sigma, sigma) for c in r0]
x = [rng.uniform(-1.0, 1.0) for _ in range(3)]
nx = math.sqrt(sum(v * v for v in x))
a = transform(axis_angle_to_R(r), ZERO3, [x])[0]
b = transform(axis_angle_to_R(r0), ZERO3, [x])[0]
dist = math.sqrt(sum((p - q) ** 2 for p, q in zip(a, b)))
self.assertLessEqual(dist, rotation_uncertainty(nx, sigma) + 1e-12)
def test_residual_lower_bound(self):
# Theorem 2: e_i(R_r, t) >= e_i(R_r0, t0) - gamma_ri - gamma_t.
P, Q, _, _, _ = scene(6, 10, 2)
rng = random.Random(4)
for _ in range(100):
sr, st = rng.uniform(0.01, 0.5), rng.uniform(0.01, 0.3)
r0 = [rng.uniform(-1.5, 1.5) for _ in range(3)]
t0 = [rng.uniform(-0.3, 0.3) for _ in range(3)]
r = [c + rng.uniform(-sr, sr) for c in r0]
t = [c + rng.uniform(-st, st) for c in t0]
e0 = residuals(transform(axis_angle_to_R(r0), ZERO3, P), t0, Q)
e = residuals(transform(axis_angle_to_R(r), ZERO3, P), t, Q)
for p, a, b in zip(P, e, e0):
g = rotation_uncertainty(math.sqrt(sum(v * v for v in p)), sr) + math.sqrt(3.0) * st
self.assertGreaterEqual(a, b - g - 1e-12)
def test_inner_search_against_grid(self):
# Brute force over a grid of translations: L is below every value
# and the best value found is within delta of the grid minimum.
P, Q, _, _, _ = scene(6, 10, 2)
moved = transform(axis_angle_to_R([0.3, -0.2, 0.5]), ZERO3, P)
delta = 0.02
for gam in (0.0, 0.05):
gammas = [gam] * len(P)
Et, tb, L = inner_bnb(moved, gammas, Q, ZERO3, 0.4, float("inf"), delta)
grid = [-0.4 + 0.8 * k / 12 for k in range(13)]
vals = [sum(max(e - gam, 0.0) ** 2 for e in residuals(moved, [x, y, z], Q))
for x in grid for y in grid for z in grid]
self.assertLessEqual(L, min(vals) + 1e-12)
self.assertLessEqual(Et, min(vals) + delta)
self.assertAlmostEqual(sum(max(e - gam, 0.0) ** 2 for e in residuals(moved, tb, Q)), Et, places=12)
def test_bad_eps(self):
P, Q, _, _, _ = scene(4, 6, 1)
with self.assertRaises(ValueError):
go_icp(P, Q, 0.0)
if __name__ == "__main__":
unittest.main()
History
Yang, Li and Jia presented Go-ICP at ICCV in 2013. The journal version, with Campbell, appeared in IEEE TPAMI in 2016, with the trimmed cost for outliers and more tests. It was the first globally optimal method for the ICP cost of 3D registration with both rotation and translation unknown. The rotation search builds on the branch and bound over rotation space of Hartley and Kahl (2009), and the trimming on the trimmed ICP of Chetverikov et al. (2002).
References
- Jiaolong Yang, Hongdong Li, Dylan Campbell and Yunde Jia, Go-ICP: A globally optimal solution to 3D ICP point-set registration, IEEE Transactions on Pattern Analysis and Machine Intelligence 38(11), 2016, 2241-2254, The angle-axis parametrization of rotations in the cube [-pi, pi]^3, Theorem 1 (the uncertainty radius of a rotation cube), Theorem 2 (the bounds of the residuals), the nested branch and bound with ICP for the upper bounds, the trimmed extension for outliers, and the 3D distance transform for closest-point distances
- Paul J. Besl and Neil D. McKay, A method for registration of 3-D shapes, IEEE Transactions on Pattern Analysis and Machine Intelligence 14(2), 1992, 239-256, The ICP algorithm and its cost, which Go-ICP minimizes globally
- Dmitry Chetverikov, Dmitry Svirko, Dmitry Stepanov and Pavel Krsek, The Trimmed Iterative Closest Point algorithm, Proceedings of the 16th International Conference on Pattern Recognition (ICPR 2002), volume 3, The trimmed cost that Go-ICP adopts for outliers
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 AT1CTF Edit this page History Report an error Markdown