Algorithm Search⌘K

Algorithmadvanced

Trimmed ICP

Also called TrICP.

ICP for partly overlapping clouds: in each iteration only the fraction xi of pairs with the least distances enters the fit. The trimmed mean squared error never rises; the result is local.

Time
Θ(N n m) worst · averageΘ(n m) best
Space
Θ(n) extra
Where
N = the number of iterations; m = the number of target points; n = the number of source points
Properties
deterministicnot exactofflineiterative
Origin
Dmitry Chetverikov, Dmitry Svirko, Dmitry Stepanov, Pavel Krsek, 2002

Trimmed ICP (TrICP) aligns a source point cloud PP of nn points to a target cloud QQ when only part of PP has a partner in QQ. It is iterative closest point with one change: after the closest-point match, it sorts the pairs by distance and keeps only the Npo=⌊ξn⌋N_{po} = \lfloor \xi n \rfloor pairs with the least squared distances, where ξ∈(0,1]\xi \in (0, 1] is the overlap, the fraction of source points that have a partner. The fit step uses only the kept pairs. This is the idea of least trimmed squares applied to registration. The trimmed mean squared error never goes up, and for finite clouds the loop stops at a fixed point. With ξ=1\xi = 1 it is plain ICP. Like ICP, it is local and needs a rough start.

In plain words

Two scans of a room taken from different places see different parts of it. Each scan has points that the other scan never saw. Plain ICP still gives each of those points a nearest partner, which is wrong, and these wrong pairs drag the answer away.

Trimmed ICP says: I expect, say, 70 percent of my points to have a real partner. In every round it pairs each point with its nearest point, as before, but then it throws away the 30 percent of pairs with the longest gaps. It fits the turn and slide to the rest only.

The points without a partner usually have the longest gaps, so they are the ones that go. You must give the overlap, or let the method guess it.

The problem

Input. A source cloud P=(p1,…,pn)P = (p_1, \ldots, p_n) and a target cloud Q={q1,…,qm}Q = \{q_1, \ldots, q_m\} in R3\mathbb{R}^3, the overlap ξ∈(0,1]\xi \in (0, 1], a start pose (R0,t0)(R_0, t_0), and stop parameters eps and tol.

Output. A pose (R,t)(R, t) with R∈SO(3)R \in SO(3) at a fixed point of the iteration. The cost is the trimmed mean squared error

e(R,t)=1Npo∑k=1Npod(k)2,di=min⁡j∣Rpi+t−qj∣,e(R, t) = \frac{1}{N_{po}} \sum_{k=1}^{N_{po}} d_{(k)}^2, \qquad d_i = \min_j |R p_i + t - q_j|,

where d(1)≤d(2)≤⋯d_{(1)} \le d_{(2)} \le \cdots are the distances in increasing order, and Npo=max⁡(3,⌊ξn⌋)N_{po} = \max(3, \lfloor \xi n \rfloor) in the reference code (three pairs are the least that fix a rotation in general position).

The algorithm

  1. TRIMMED-ICP(P, Q, ξ, R0, t0, eps, tol)
  2. 1R ← R0 ; t ← t0 ; N_po ← max(3, ⌊ξ n⌋) ; e_prev ← ∞
  3. 2repeat (up to an iteration cap)
  4. 3c(i) ← index of the closest q_j to R p_i + t ; d_i² ← |R p_i + t - q_c(i)|²
  5. 4S ← the N_po indices i with the least d_i²
  6. 5e ← (1/N_po) Σ_{i ∈ S} d_i²
  7. 6if e ≤ eps or e_prev - e ≤ tol then return R, t
  8. 7(R, t) ← KABSCH((p_i), (q_c(i))) over i ∈ S ▷ with the sign fix
  9. 8e_prev ← e
  10. 9return R, t

Line L3 is the closest-point step of ICP; the code uses brute force. Line L4 is the trimming. The code sorts the nn distances; a selection algorithm such as quickselect finds the NpoN_{po} least ones in O(n)O(n) expected time. Line L5 is the trimmed MSE of the current pose. Line L6 stops when the error is small enough, or when it no longer falls by more than tol. Line L7 is the Kabsch fit with R=Vdiag⁡(1,1,d) UTR = V \operatorname{diag}(1, 1, d)\, U^{\mathsf T}, applied to the kept pairs only.

Example

The test scene has 40 shared points drawn in [−1,1]3[-1, 1]^3 (seed 1). The target QQ holds these points moved by a rotation of 12 degrees about (1,−1,2)(1, -1, 2) and the translation (0.1,0.05,−0.08)(0.1, 0.05, -0.08), plus 10 points in [−2.5,−1.5]3[-2.5, -1.5]^3 that the source does not see. The source PP holds the 40 shared points in their original place, plus 14 points in the slab 1.2≤x≤1.81.2 \le x \le 1.8 that the target does not see. So n=54n = 54, m=50m = 50, and the true overlap is 40/54≈0.74140/54 \approx 0.741. The start is the identity, with eps =0= 0 and tol =0= 0.

With ξ=40/54\xi = 40/54, so Npo=40N_{po} = 40:

iteration after line L5 after line L7 (kept pairs)
1 0.0412 0.0105
2 0.00226 4.7e-32
3 4.7e-32 4.7e-32
4 4.7e-32, stop

The pose is exact up to rounding. The values never go up, as the proof says. The other values of ξ\xi give:

ξ\xi NpoN_{po} final trimmed MSE rotation error translation error
0.6 32 about 2e-31 0 0
40/54 40 4.7e-32 0 0
0.85 45 0.0425 2.94 degrees (-0.063, -0.013, -0.020)
1 (plain ICP) 54 0.145 8.77 degrees (-0.185, -0.073, -0.017)

A ξ\xi below the true overlap still finds the exact pose here, because the kept pairs are all true pairs. A ξ\xi above it forces some of the 14 unseen points into the fit and biases the result. Plain ICP keeps all of them and is the worst.

Correctness

Claim: with eps =0= 0 and tol =0= 0, TrICP stops after finitely many iterations, the trimmed MSE never rises, the rotation is proper, and the returned pose is a least squares fit to a set of NpoN_{po} pairs that are closest-point pairs with the least distances at that pose. The key inequality is ek≥Fk(Rk+1,tk+1)≥ek+1e_k \ge F_k(R_{k+1}, t_{k+1}) \ge e_{k+1}. Line L7 minimizes the cost FkF_k of the kept pairs, so it is no worse than the old pose. Then line L3 can only shorten each distance, and line L4 picks the NpoN_{po} shortest, whose sum is at most the sum over the old kept set. The full proof is in proofs/correctness.md. Chetverikov, Stepanov and Krsek (2005) prove the monotone convergence of TrICP.

Proof: The trimmed mean squared error of TrICP never increases, and TrICP stopsfull

We use the notation of the page. The source is P=(p1,…,pn)P = (p_1, \ldots, p_n) and the target is Q={q1,…,qm}Q = \{q_1, \ldots, q_m\} in R3\mathbb{R}^3. The overlap is ξ∈(0,1]\xi \in (0, 1], and line L1 sets the number of kept pairs to Npo=max⁡(3,⌊ξn⌋)N_{po} = \max(3, \lfloor \xi n \rfloor), with Npo≤nN_{po} \le n. For a pose (R,t)(R, t) let di(R,t)=min⁡j∣Rpi+t−qj∣d_i(R, t) = \min_j |R p_i + t - q_j|. For a set SS of NpoN_{po} source indices and a match cc, let

F(R,t,S,c)=1Npo∑i∈S∣Rpi+t−qc(i)∣2,e(R,t)=min⁡∣S∣=Npo1Npo∑i∈Sdi(R,t)2.F(R, t, S, c) = \frac{1}{N_{po}} \sum_{i \in S} |R p_i + t - q_{c(i)}|^2, \qquad e(R, t) = \min_{|S| = N_{po}} \frac{1}{N_{po}} \sum_{i \in S} d_i(R, t)^2 .

So e(R,t)e(R, t) is the mean of the NpoN_{po} least squared closest-point distances, the trimmed MSE. In iteration kk, line L3 computes the closest-point match ckc_k of the pose (Rk,tk)(R_k, t_k), line L4 the set SkS_k of the NpoN_{po} indices with the least distances, and line L5 the value ek=F(Rk,tk,Sk,ck)=e(Rk,tk)e_k = F(R_k, t_k, S_k, c_k) = e(R_k, t_k). Line L7 computes (Rk+1,tk+1)=FIT(Sk,ck)(R_{k+1}, t_{k+1}) = \mathrm{FIT}(S_k, c_k), the Kabsch motion with the sign fix for the pairs (pi,qck(i))(p_i, q_{c_k(i)}), i∈Ski \in S_k. We assume exact arithmetic, eps =0= 0 and tol =0= 0.

Claim. (a) ek≥F(Rk+1,tk+1,Sk,ck)≥ek+1e_k \ge F(R_{k+1}, t_{k+1}, S_k, c_k) \ge e_{k+1} for every kk, so the trimmed MSE never increases. (b) TrICP stops at line L6 after finitely many iterations. (c) When it stops, there is a set SS of NpoN_{po} indices and a closest-point match cc of the returned pose (R,t)(R, t) such that SS holds NpoN_{po} least distances at (R,t)(R, t) and (R,t)(R, t) minimizes F(⋅,⋅,S,c)F(\cdot, \cdot, S, c). (d) With ξ=1\xi = 1 and n≥3n \ge 3, TrICP is point-to-point ICP.

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

Proof. With SS and cc fixed, NpoFN_{po} F is the least squares cost of the matched pairs (pi,qc(i))(p_i, q_{c(i)}), i∈Si \in S. The Kabsch algorithm with the sign fix returns a global minimizer of that cost over proper rotations and translations. □\square

Lemma 2 (the match and trim step). For a fixed pose and every set SS of NpoN_{po} indices and every match cc, e(R,t)≤F(R,t,S,c)e(R, t) \le F(R, t, S, c).

Proof. Each term ∣Rpi+t−qc(i)∣2|R p_i + t - q_{c(i)}|^2 is at least di(R,t)2d_i(R, t)^2. The sum of di2d_i^2 over SS is at least the sum of the NpoN_{po} least values of di2d_i^2, which is Npo e(R,t)N_{po}\, e(R, t). □\square

Proof of (a). (Rk,tk)(R_k, t_k) is one candidate for the fit of (Sk,ck)(S_k, c_k), so Lemma 1 gives F(Rk+1,tk+1,Sk,ck)≤F(Rk,tk,Sk,ck)=ekF(R_{k+1}, t_{k+1}, S_k, c_k) \le F(R_k, t_k, S_k, c_k) = e_k. Lemma 2 at the pose (Rk+1,tk+1)(R_{k+1}, t_{k+1}) gives ek+1≤F(Rk+1,tk+1,Sk,ck)e_{k+1} \le F(R_{k+1}, t_{k+1}, S_k, c_k). □\square

Proof of (b). If TrICP does not stop in iterations 1,…,K1, \ldots, K, then e0>e1>⋯>eKe_0 > e_1 > \cdots > e_K, because line L6 stops when ek−1−ek≤0e_{k-1} - e_k \le 0. If (Sj,cj)=(Sk,ck)(S_j, c_j) = (S_k, c_k) for some j<k≤K−1j < k \le K - 1, then (Rj+1,tj+1)=(Rk+1,tk+1)(R_{j+1}, t_{j+1}) = (R_{k+1}, t_{k+1}), since FIT is deterministic, and ej+1=ek+1e_{j+1} = e_{k+1}, a contradiction. The pairs (Sk,ck)(S_k, c_k) take at most (nNpo)mn\binom{n}{N_{po}} m^n values, so KK is at most this number, and TrICP stops. □\square

Proof of (c). If TrICP stops by ek≤e_k \le eps =0= 0, then ek=0e_k = 0, so (Rk,tk)(R_k, t_k) minimizes F(⋅,⋅,Sk,ck)≥0F(\cdot, \cdot, S_k, c_k) \ge 0, and SkS_k, ckc_k are as required. Otherwise it stops in iteration k≥1k \ge 1 with ek=ek−1e_k = e_{k-1}. By part (a), F(Rk,tk,Sk−1,ck−1)=ek=e(Rk,tk)F(R_k, t_k, S_{k-1}, c_{k-1}) = e_k = e(R_k, t_k). Every term in this sum is at least the matching di(Rk,tk)2d_i(R_k, t_k)^2, and the sum equals the sum of the NpoN_{po} least values. So every term equals di2d_i^2, and Sk−1S_{k-1} holds NpoN_{po} least distances at (Rk,tk)(R_k, t_k). We can extend ck−1c_{k-1} on Sk−1S_{k-1} by ckc_k outside Sk−1S_{k-1} to a closest-point match cc of (Rk,tk)(R_k, t_k), with F(⋅,⋅,Sk−1,c)=F(⋅,⋅,Sk−1,ck−1)F(\cdot, \cdot, S_{k-1}, c) = F(\cdot, \cdot, S_{k-1}, c_{k-1}). By Lemma 1, (Rk,tk)=FIT(Sk−1,ck−1)(R_k, t_k) = \mathrm{FIT}(S_{k-1}, c_{k-1}) minimizes it. □\square

Proof of (d). With ξ=1\xi = 1 and n≥3n \ge 3, Npo=nN_{po} = n, so Sk={1,…,n}S_k = \{1, \ldots, n\}, and ee and FF are the cost of point-to-point ICP. The fit, the costs and the stop test are those of ICP with tol =0= 0, except that ICP also stops when the match repeats; a repeated match gives the same fit and the same cost, so TrICP stops one iteration later at the same pose. □\square

Theorem. With eps =0= 0 and tol =0= 0, TrICP returns after finitely many iterations a pose with a proper rotation. The trimmed MSE of the poses it visits never increases, and the returned pose is a fixed point of the match, trim and fit steps in the sense of (c).

Proof. Parts (a), (b) and (c), and the sign fix of Lemma 1 for det⁡R=+1\det R = +1. ■\blacksquare

What this proof does not give. As for ICP, the result is local: the fixed point can be far from the true pose, and it need not be a local minimum of ee when distances tie. The proof also says nothing about the choice of ξ\xi. If ξ\xi is larger than the true overlap, some kept pairs are wrong, and the fit is biased. The rule of Chetverikov et al. that chooses ξ\xi by minimizing e(ξ)/ξ1+λe(\xi)/\xi^{1 + \lambda} is a heuristic, not part of this theorem.

Complexity

The model is the real RAM. Per iteration, line L3 costs Θ(nm)\Theta(n m) by brute force, or about nlog⁡mn \log m with a k-d tree on typical 3D data (an expected cost, not a worst case). Line L4 costs Θ(nlog⁡n)\Theta(n \log n) by sorting, or O(n)O(n) expected with quickselect. Lines L5 and L7 cost Θ(n)\Theta(n). So an iteration costs Θ(nm)\Theta(n m), and NN iterations cost Θ(Nnm)\Theta(N n m). The best case is two passes, Θ(nm)\Theta(n m). The extra space is Θ(n)\Theta(n).

The number of iterations NN is finite by the proof, but the bound there is a crude count of match and trim sets. Measured counts are benchmark results.

Properties

  • Monotone. The trimmed MSE never rises.
  • Local. As for ICP, the result depends on the start pose.
  • Needs the overlap. The user gives ξ\xi, or an outer search chooses it.
  • Contains ICP. With ξ=1\xi = 1 every pair is kept, and TrICP is point-to-point ICP.
  • Breakdown. Up to a fraction 1−ξ1 - \xi of source points without a partner can be ignored, if they have the longest distances. This is not guaranteed: an unseen point can lie close to some target point by chance.

Variants and improvements

  • Automatic overlap. Chetverikov, Stepanov and Krsek (2005) run TrICP for a range of ξ\xi and choose the value that minimizes an objective that divides the trimmed MSE by a power of ξ\xi, so that a larger overlap is preferred when the error allows it. The form e(ξ)/ξ1+λe(\xi)/\xi^{1 + \lambda} with λ=2\lambda = 2 comes from slides of the authors; we did not confirm it in the paper. A one-dimensional search, such as golden section search, can run this outer loop; it assumes that the objective has one minimum in the range of ξ\xi, which is not proved.
  • Distance threshold. Many ICP codes drop pairs farther than a fixed distance instead. This needs a threshold in distance units instead of a fraction.
  • Robust weights. Weights from an M-estimator reduce the effect of far pairs smoothly instead of cutting them.
  • Other error metrics. The same trimming works with the point-to-plane error of point-to-plane ICP and in generalized ICP.
  • Global search. Go-ICP uses trimming inside its branch and bound search to handle outliers.

When to use it

Use TrICP when the two clouds overlap only in part and a rough pose is known: scans of a scene from different places, a model against a scan that sees one side of it, or a cloud with clutter. If the overlap is roughly known, give it. If not, run the automatic choice or try a few values and compare the fit. Prefer a ξ\xi a little below the true overlap: in the example, a too small ξ\xi still worked, and a too large one did not. For heavy outlier rates with no rough pose, use a robust global method such as RANSAC on feature matches or TEASER first.

Pitfalls

  • The trimmed sum without the trimmed fit. Computing ee over the kept set in line L5 and then fitting all nn pairs in line L7 loses the robustness and the proof of monotone decrease. Fit only the pairs in SS.
  • Dividing by nn in line L5. The MSE must be divided by NpoN_{po}. Dividing by nn does not change the pose, but it makes errors for different ξ\xi incomparable, which breaks the automatic choice of the overlap.
  • A ξ\xi that is too large in line L1. Pairs without a true partner enter the fit and bias it, as in the row ξ=0.85\xi = 0.85 of the example.
  • A ξ\xi that is too small in line L1. Fewer pairs make the fit noisier, and with very few pairs the kept points may lie on one patch and leave a slide free.
  • No floor on NpoN_{po}. With ⌊ξn⌋<3\lfloor \xi n \rfloor < 3 the fit in line L7 is not defined in general. Keep at least three pairs.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

cvgeom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Camera geometry and synthetic scenes for the computer vision pages.

Conventions (prompts of the area, also stated on the pages):
- The camera frame has X to the right, Y down and Z forward. A point is in
  front of the camera if Z > 0.
- K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]] in pixels.
- A world point Xw maps to the camera frame by Xc = R Xw + t. The camera
  matrix is P = K [R | t], and the center is C = -R^T t.
- Rotations are active and right-handed. Quaternions are (w, x, y, z) in the
  Hamilton convention.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import math
import random
from typing import Dict, List, Optional, Sequence, Tuple

from cvla import det, matvec, mul, solve, transpose

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


def to_h(x: Sequence[float]) -> Vector:
    """Append a 1: the homogeneous vector of a point."""
    return [float(v) for v in x] + [1.0]


def from_h(x: Sequence[float]) -> Vector:
    """Divide by the last entry and drop it. Raises ValueError if the last
    entry is zero (a point at infinity)."""
    w = x[-1]
    if w == 0:
        raise ValueError("from_h: point at infinity")
    return [v / w for v in x[:-1]]


def make_K(fx: float, fy: float, cx: float, cy: float, s: float = 0.0) -> Matrix:
    """The intrinsic matrix [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
    return [[float(fx), float(s), float(cx)],
            [0.0, float(fy), float(cy)],
            [0.0, 0.0, 1.0]]


def camera_matrix(K: Sequence[Sequence[float]], R: Sequence[Sequence[float]],
                  t: Sequence[float]) -> Matrix:
    """The 3 x 4 camera matrix P = K [R | t]."""
    rt = [list(R[i]) + [t[i]] for i in range(3)]
    return mul(K, rt)


def project(P: Sequence[Sequence[float]], X):
    """Pixel coordinates (u, v) of a point X under the camera P.

    X is a 3D point (3 entries) or a homogeneous point (4 entries). If X is
    a list of points, the result is the list of their projections."""
    if len(X) > 0 and isinstance(X[0], (list, tuple)):
        return [project(P, x) for x in X]
    xh = to_h(X) if len(X) == 3 else list(X)
    return from_h(matvec(P, xh))


def camera_center(P: Sequence[Sequence[float]]) -> Vector:
    """The center C of a finite camera P = [M | p4]: C = -M^-1 p4, so that
    P (C, 1) = 0."""
    m = [list(row[:3]) for row in P]
    p4 = [row[3] for row in P]
    return [-v for v in solve(m, p4)]


def rot_x(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the X axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def axis_angle_to_R(axis: Sequence[float], theta: Optional[float] = None) -> Matrix:
    """Rotation by theta (radians) about the axis, by the right-hand rule
    (Rodrigues formula). The axis need not be a unit vector. If theta is
    None, axis is the rotation vector w = theta a, with theta = ||w||."""
    n = math.sqrt(sum(float(v) * float(v) for v in axis))
    if theta is None:
        theta = n
    if n == 0.0 or theta == 0.0:
        return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    x, y, z = (float(v) / n for v in axis)
    c, s = math.cos(theta), math.sin(theta)
    d = 1.0 - c
    return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
            [y * x * d + z * s, c + y * y * d, y * z * d - x * s],
            [z * x * d - y * s, z * y * d + x * s, c + z * z * d]]


def quat_to_R(q: Sequence[float]) -> Matrix:
    """Rotation matrix of the quaternion q = (w, x, y, z), Hamilton
    convention. q is normalized first; q and -q give the same matrix."""
    n = math.sqrt(sum(float(v) * float(v) for v in q))
    if n == 0.0:
        raise ValueError("quat_to_R: zero quaternion")
    w, x, y, z = (float(v) / n for v in q)
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def random_rotation(rng: random.Random) -> Matrix:
    """A rotation drawn from the uniform (Haar) distribution: a uniform
    random unit quaternion by the method of Shoemake (1992)."""
    u1, u2, u3 = rng.random(), rng.random(), rng.random()
    a, b = math.sqrt(1.0 - u1), math.sqrt(u1)
    q = (b * math.cos(2 * math.pi * u3), a * math.sin(2 * math.pi * u2),
         a * math.cos(2 * math.pi * u2), b * math.sin(2 * math.pi * u3))
    return quat_to_R(q)


def _small_rotation(rng: random.Random, max_angle: float) -> Matrix:
    axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
    return axis_angle_to_R(axis, rng.uniform(0.0, max_angle))


def random_scene(rng: random.Random, n: int = 20, n_cams: int = 2,
                 K: Optional[Sequence[Sequence[float]]] = None,
                 cams: Optional[Sequence[Tuple]] = None,
                 radius: float = 1.0, distance: float = 5.0,
                 max_angle: float = 0.3, planar: bool = False,
                 first_identity: bool = False,
                 size: Optional[Tuple[float, float]] = None,
                 min_depth: float = 0.1) -> Dict[str, list]:
    """A synthetic scene with known cameras and points.

    Cameras: if cams is given, it is a list of (K, R, t) and is used as it
    is. Otherwise n_cams cameras look at the world origin from the distance
    `distance`. Each one is the camera at center (0, 0, -distance) with
    R = I, turned about the origin by a random rotation of angle at most
    max_angle (radians). K defaults to make_K(800, 800, 320, 240). With
    first_identity, the world frame is moved to the frame of camera 0, so
    that camera 0 has R = I and t = 0 (the points move with it).

    Points: n points drawn uniformly in the cube [-radius, radius]^3 (with
    Z = 0 if planar, before any move of the world frame). A point is kept
    only if its depth is at least min_depth in every camera, and, if size =
    (W, H) is given, if its projection lies in [0, W] x [0, H] in every
    camera. Raises ValueError if 1000 n draws are not enough.

    Returns a dict with lists "K", "R", "t", "P" (one entry per camera),
    "X" (the 3D points) and "x" (x[i][j] is the pixel of point j in
    camera i, without noise)."""
    if cams is not None:
        Ks = [[list(r) for r in c[0]] for c in cams]
        Rs = [[list(r) for r in c[1]] for c in cams]
        ts = [list(c[2]) for c in cams]
    else:
        k0 = [list(r) for r in K] if K is not None else make_K(800, 800, 320, 240)
        Ks, Rs, ts = [], [], []
        c0 = [0.0, 0.0, -float(distance)]
        for _ in range(n_cams):
            q = _small_rotation(rng, max_angle)
            r = transpose(q)
            center = matvec(q, c0)
            Ks.append([list(row) for row in k0])
            Rs.append(r)
            ts.append([-v for v in matvec(r, center)])
    pts: List[Vector] = []
    tries = 0
    while len(pts) < n:
        tries += 1
        if tries > 1000 * max(n, 1):
            raise ValueError("random_scene: cannot place the points")
        x = [rng.uniform(-radius, radius) for _ in range(3)]
        if planar:
            x[2] = 0.0
        ok = True
        for k, r, t in zip(Ks, Rs, ts):
            xc = [a + b for a, b in zip(matvec(r, x), t)]
            if xc[2] < min_depth:
                ok = False
                break
            if size is not None:
                u = (k[0][0] * xc[0] + k[0][1] * xc[1]) / xc[2] + k[0][2]
                v = k[1][1] * xc[1] / xc[2] + k[1][2]
                if not (0.0 <= u <= size[0] and 0.0 <= v <= size[1]):
                    ok = False
                    break
        if ok:
            pts.append(x)
    if first_identity and Rs:
        r0, t0 = Rs[0], ts[0]
        pts = [[a + b for a, b in zip(matvec(r0, x), t0)] for x in pts]
        r0t = transpose(r0)
        newR, newt = [], []
        for r, t in zip(Rs, ts):
            rr = mul(r, r0t)
            newR.append(rr)
            newt.append([a - b for a, b in zip(t, matvec(rr, t0))])
        Rs, ts = newR, newt
        Rs[0] = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
        ts[0] = [0.0, 0.0, 0.0]
    Ps = [camera_matrix(k, r, t) for k, r, t in zip(Ks, Rs, ts)]
    xs = [[project(p, x) for x in pts] for p in Ps]
    return {"K": Ks, "R": Rs, "t": ts, "P": Ps, "X": pts, "x": xs}


def add_noise(rng: random.Random, pts: Sequence[Sequence[float]], sigma: float) -> List[Vector]:
    """A copy of the points with independent Gaussian noise of standard
    deviation sigma added to every coordinate."""
    return [[float(v) + rng.gauss(0.0, sigma) for v in p] for p in pts]


def self_test() -> None:
    """Check random_scene and quat_to_R. Raises AssertionError."""
    rng = random.Random(11)
    scene = random_scene(rng, n=30, n_cams=4)
    for r, t in zip(scene["R"], scene["t"]):
        for x in scene["X"]:
            assert matvec(r, x)[2] + t[2] > 0.0
    for _ in range(5):
        q = [rng.gauss(0.0, 1.0) for _ in range(4)]
        r = quat_to_R(q)
        rtr = mul(transpose(r), r)
        assert all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) <= 1e-12
                   for i in range(3) for j in range(3))
        assert abs(det(r) - 1.0) <= 1e-12


if __name__ == "__main__":
    self_test()
cvla.py 494 lines
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import cmath
import math
from typing import List, Sequence, Tuple

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

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


# ---------------------------------------------------------------- basics

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """The cross product a x b of two 3-vectors."""
    return [a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0]]


def skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


# ---------------------------------------------------------- polynomials

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
trimmed_icp.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trimmed-icp/. The authors are listed in prov/J43W5E.jsonl.
"""Trimmed iterative closest point (TrICP) of Chetverikov, Svirko,
Stepanov and Krsek.

Given a source cloud P (n points), a target cloud Q and the overlap xi in
(0, 1], only the N_po = floor(xi n) source points with the smallest
closest-point distances take part in each fit. Each iteration matches every
moved source point to its closest target point, keeps the N_po pairs with
the least squared distances, and replaces (R, t) by the rigid motion that
best fits those pairs (Kabsch, with the sign fix). The trimmed mean squared
error never goes up. With xi = 1 this is plain ICP.

The closest-point search is brute force, Theta(n m) per iteration; the
trimming sorts the n distances, Theta(n log n).
"""

from __future__ import annotations

import math
from typing import List, Optional, Sequence, Tuple

from cvla import det, mul, svd, 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 to it (brute force; ties go to the lowest index)."""
    idx, d2 = [], []
    for x, y, z in pts:
        best, bj = float("inf"), -1
        for j, q in enumerate(target):
            dx, dy, dz = x - q[0], y - q[1], z - q[2]
            d = dx * dx + dy * dy + dz * dz
            if d < best:
                best, bj = d, j
        idx.append(bj)
        d2.append(best)
    return idx, d2


def least_k(d2: Sequence[float], k: int) -> List[int]:
    """The indices of the k smallest values (ties by index)."""
    return sorted(range(len(d2)), key=lambda i: (d2[i], i))[:k]


def best_rigid_transform(P, Y) -> Tuple[Matrix, Vector]:
    """Kabsch: the rotation (det +1) and translation that minimize
    sum ||R p_i + t - y_i||^2, with R = V diag(1, 1, d) U^T."""
    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.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 trimmed_icp(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]], xi: float,
                R0: Optional[Sequence[Sequence[float]]] = None,
                t0: Optional[Sequence[float]] = None,
                max_iter: int = 100, eps: float = 0.0,
                tol: float = 0.0) -> Tuple[Matrix, Vector, List[float]]:
    """Trimmed ICP with overlap xi from the start pose (R0, t0).

    Stops when the trimmed MSE is at most eps, when it falls by at most tol
    in one iteration, or after max_iter iterations. Returns (R, t, costs):
    costs lists the trimmed MSE after each matching and trimming step and
    after each fit step, in order, so it never goes up."""
    if not 0.0 < xi <= 1.0:
        raise ValueError("trimmed_icp: xi must be in (0, 1]")
    n = len(P)
    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
    npo = max(3, int(math.floor(xi * n + 1e-9)))  # @line L1
    if npo > n:
        raise ValueError("trimmed_icp: need at least 3 source points")
    e_prev = float("inf")  # @line L1
    costs: List[float] = []
    for _ in range(max_iter):  # @line L2
        idx, d2 = closest_points(transform(R, t, P), Q)  # @line L3
        keep = least_k(d2, npo)  # @line L4
        e = sum(d2[i] for i in keep) / npo  # @line L5
        costs.append(e)
        if e <= eps or e_prev - e <= tol:  # @line L6
            return R, t, costs  # @line L6
        Ps, Ys = [P[i] for i in keep], [Q[idx[i]] for i in keep]
        R, t = best_rigid_transform(Ps, Ys)  # @line L7
        moved = transform(R, t, Ps)
        costs.append(sum((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2
                         for a, b in zip(moved, Ys)) / npo)
        e_prev = e  # @line L8
    return R, t, costs  # @line L9
test_trimmed_icp.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trimmed-icp/. The authors are listed in prov/J43W5E.jsonl.
import itertools
import math
import random
import unittest

from cvgeom import add_noise, axis_angle_to_R
from cvla import det, mul, transpose
from trimmed_icp import (best_rigid_transform, closest_points, least_k,
                         transform, trimmed_icp)

TOL_ICP = 1e-6


def rot_angle(R1, R2):
    """The angle of R1^T R2: arccos((tr - 1) / 2), computed with atan2."""
    m = mul(transpose(R1), R2)
    c = (m[0][0] + m[1][1] + m[2][2] - 1.0) / 2.0
    s = 0.5 * math.sqrt((m[2][1] - m[1][2]) ** 2 + (m[0][2] - m[2][0]) ** 2 + (m[1][0] - m[0][1]) ** 2)
    return math.atan2(s, c)


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


def partial_overlap_scene(seed):
    """40 source points seen in the target, 14 source points that are not
    (they lie in a slab next to the cloud), and 10 target points that the
    source does not see. The true overlap is 40 / 54."""
    rng = random.Random(seed)
    shared = cloud(rng, 40)
    extra = [[rng.uniform(1.2, 1.8), rng.uniform(-1, 1), rng.uniform(-1, 1)] for _ in range(14)]
    R = axis_angle_to_R([1.0, -1.0, 2.0], math.radians(12.0))
    t = [0.1, 0.05, -0.08]
    Q = transform(R, t, shared) + cloud(rng, 10, -2.5, -1.5)
    rng.shuffle(Q)
    return shared + extra, Q, R, t


def plain_icp(P, Q, iters=100):
    """Reference: point-to-point ICP written out directly."""
    R, t = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [0.0, 0.0, 0.0]
    for _ in range(iters):
        idx, _ = closest_points(transform(R, t, P), Q)
        R2, t2 = best_rigid_transform(P, [Q[j] for j in idx])
        if rot_angle(R, R2) == 0.0 and t2 == t:
            break
        R, t = R2, t2
    return R, t


class TestTrimmedICP(unittest.TestCase):
    def test_exact_recovery_with_outliers(self):
        P, Q, R, t = partial_overlap_scene(1)
        Rf, tf, costs = trimmed_icp(P, Q, xi=40.0 / 54.0)
        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_plain_icp_is_biased_on_the_same_scene(self):
        P, Q, R, _ = partial_overlap_scene(1)
        Rf, _, _ = trimmed_icp(P, Q, xi=1.0)
        self.assertGreater(rot_angle(R, Rf), math.radians(1.0))

    def test_trimmed_error_never_goes_up(self):
        P, Q, _, _ = partial_overlap_scene(2)
        rng = random.Random(3)
        P = add_noise(rng, P, 0.02)
        for xi in (0.5, 0.7, 0.9):
            _, _, costs = trimmed_icp(P, Q, xi=xi)
            for a, b in zip(costs, costs[1:]):
                self.assertLessEqual(b, a + 1e-12)

    def test_xi_one_is_plain_icp(self):
        rng = random.Random(4)
        P = cloud(rng, 25)
        Q = add_noise(rng, transform(axis_angle_to_R([0, 1, 0], 0.3), [0.1, 0, 0], P), 0.05)
        Rf, tf, _ = trimmed_icp(P, Q, xi=1.0)
        Rr, tr = plain_icp(P, Q)
        self.assertLess(rot_angle(Rf, Rr), 1e-9)
        self.assertLess(max(abs(a - b) for a, b in zip(tf, tr)), 1e-9)

    def test_trimming_keeps_the_best_subset(self):
        # Brute force over all subsets of size k.
        rng = random.Random(5)
        for _ in range(20):
            d2 = [rng.random() for _ in range(8)]
            for k in (3, 5, 7):
                got = sum(d2[i] for i in least_k(d2, k))
                best = min(sum(c) for c in itertools.combinations(d2, k))
                self.assertAlmostEqual(got, best, places=12)

    def test_bad_overlap(self):
        with self.assertRaises(ValueError):
            trimmed_icp([[0.0, 0.0, 0.0]] * 5, [[0.0, 0.0, 0.0]], xi=0.0)


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

History

Chetverikov, Svirko, Stepanov and Krsek presented the Trimmed ICP at ICPR in 2002. The method uses the least trimmed squares idea of Rousseeuw (1984) inside the ICP loop of Besl and McKay (1992). In 2005 Chetverikov, Stepanov and Krsek published the journal version in Image and Vision Computing, with the proof of monotone convergence, an automatic choice of the overlap, and tests on partly overlapping 3D scans.

References

  1. 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 TrICP algorithm: the number of kept pairs N_po from the overlap, the trimmed sum of squares and the stop rules
  2. Dmitry Chetverikov, Dmitry Stepanov and Pavel Krsek, Robust Euclidean alignment of 3D point sets: the trimmed iterative closest point algorithm, Image and Vision Computing 23(3), 2005, 299-309, The algorithm, the proof that the trimmed mean squared error converges monotonically, the automatic choice of the overlap, and the tests with partial overlap and noise
  3. Peter J. Rousseeuw, Least median of squares regression, Journal of the American Statistical Association 79(388), 1984, 871-880, The least trimmed squares estimator, which sums only the smallest squared residuals
  4. 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 TrICP trims, and its monotone convergence

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example