Algorithmadvanced
4-points congruent sets
Also called 4PCS, Super4PCS.
Global rigid registration that finds coplanar four-point bases in one cloud and their affine-invariant ratio matches in the other, verified like RANSAC.
- Solves
- Point cloud registration
- Time
- O(N (n^2 + k n^2)) worstO(N (n^2 + k n)) averageΘ(N n^2) best
- Space
- O(n^2 + k) extra
- Where
- N = the number of trials; k = the number of candidate sets in a trial; n = the number of points in each cloud
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dror Aiger, Niloy J. Mitra, Daniel Cohen Or, 2008
4-points congruent sets (4PCS) aligns two point clouds and that overlap only in part, from any start pose and without features or correspondences. It follows the RANSAC pattern: guess a motion from a small sample, then count how many points it explains. The sample is a base of four nearly coplanar points of whose two segments and cross at a point . The two ratios at which cuts the segments do not change under any affine map, and so not under a rigid motion. So 4PCS does not try all 4-tuples of . It finds the pairs of at the two segment lengths, computes on each pair the point that the ratio gives, and keeps the pairs of pairs whose points meet. Each such 4-tuple is a candidate image of the base. The best rigid motion from the base to the candidate is scored by the largest common pointset (LCP): the number of points of that land within of a point of . The best motion over several trials wins.
In plain words
Pick four points on the first scan that lie on one flat patch, like the corners of a kite, and draw its two crossing sticks. Note where the sticks cross: say a third of the way along one stick and half way along the other. These fractions stay the same however the kite is turned or moved.
In the second scan, find all pairs of points as far apart as the first stick, and mark the point a third of the way along each. Do the same for the second stick at half way. Where two marks meet, the four ends may be the kite.
For each such kite, move the first scan onto it and count how many points land on points of the second scan. Try a few kites and keep the best move.
The problem
Input. Two finite sets and in , each with points, that sample overlapping parts of one surface; an error bound ; and a number of trials .
Output. A rigid motion with that tries to maximize the LCP score
4PCS is a randomized search for a large LCP. It gives no guarantee of the maximum. This is global point cloud registration: the result does not depend on the start pose.
The algorithm
The base and its invariants. Pick three points of , far apart but not farther than the expected size of the overlap. Pick a fourth point close to their plane, and pair the four points into two segments that cross: and meet at . Let
If an affine map sends the base to , then the image segments cross at , at the same ratios and .
The search in Q. For a pair at a distance near , the image of would be . For a pair at a distance near , it would be . A 4-tuple of that is congruent to the base, up to , has . Each pair is used in both orders, because the order of and is not known.
4PCS(P, Q, δ, N)- 1
for trial = 1 .. N - 2
(a, b, c, d) ← a wide, nearly coplanar base of P whose segments ab and cd meet at e - 3
r₁ ← |a - e| / |a - b| ; r₂ ← |c - e| / |c - d| ; d₁ ← |a - b| ; d₂ ← |c - d| - 4
R₁ ← ordered pairs of Q at distance d₁ ± δ ; R₂ ← ordered pairs at distance d₂ ± δ - 5
U ← {(i, j, k, l) : (i, j) ∈ R₁, (k, l) ∈ R₂, |q_i + r₁(q_j - q_i) - q_k - r₂(q_l - q_k)| ≤ δ} - 6
for each (i, j, k, l) in U: T ← best rigid motion from (a, b, c, d) to (q_i, q_j, q_k, q_l) - 7
if T fits the four points: score T by LCP(T) ; keep the best - 8
return the best T
Line L2 chooses the base. The reference code takes the widest of a few random triangles whose sides are at most a given width, then the point nearest to their plane for which one of the three ways to pair the four points gives two segments that meet within . Line L3 computes the invariants. Line L4 finds the pairs by brute force over all pairs; the paper uses a faster search. Line L5 puts the points in a grid of cubes of side , a hash table of cells, and looks up each in its cube and the 26 around it. Line L6 fits the motion by the SVD with the sign fix of Umeyama. Line L7 drops a candidate if a base point is more than from its partner after the fit, since the ratios also accept affine images that are not congruent, and then scores the rest with the same grid on . The paper scores on a random sample of to save time.
Example
Take the base , , , in the plane . The segment is and the segment is . They meet where and , so , , and . So , , and .
Let be the base and four more points, , , and . Let be turned by 90 degrees about the axis and moved by , plus two outliers and . So are the images of : , , , . With :
- has 45 pairs. Only is at the distance 4.472, so holds and .
- Three pairs are at the distance 4.243: , , and , where is an outlier. holds the six ordered pairs.
- With , both orders of give the midpoint . The pair gives as well. No other point of is near. So has two tuples: and .
- The tuple fits exactly: the 90 degree turn and the shift , with LCP 8 of 8.
- The tuple has the same ratios, because is symmetric, but it is only an affine image of the base, a mirror image. The best rigid fit leaves a residual of 0.81, so line L7 drops it. Its LCP would be 0.
On a larger case, a curved patch of 200 points split into two clouds of 100 points that share about half their points, with noise of standard deviation 0.003 and , 30 trials found between 2300 and 4100 candidate sets, and the best LCP gave a rotation error between 0.27 and 1.17 degrees in each of six random cases.
Correctness
If a trial picks a base that lies in the overlap, then that trial finds the image of the base. Suppose each base point has a partner in within of its image under the true motion , and plus the gap between the two segments is at most . A rigid motion keeps distances, so both pairs pass line L4. The point is a weighted mean of points within of and , so it is within of ; the same holds for the other pair, so the two points meet within in line L5. The Kabsch fit of the four points has a residual at most , because itself has a sum of squares at most . So line L7 scores a motion close to . The full proof is in proofs/correctness.md.
The method is still randomized: the claim needs a good base, which each trial finds only with some probability. And the motion with the best LCP need not be the true one when the shape has symmetries or the overlap is small.
Proof: A trial whose base lies in the overlap finds the image of the basefull
We use the notation of the page and of the reference code. A trial picks a base from . The lines and have closest points and , with , and the base is accepted when the gap is at most . Let and . Line L4 collects the ordered pairs of with , and the same for . Line L5 keeps a 4-tuple when . Line L6 fits a rigid motion by the Kabsch method and drops the tuple if a base point is more than from its partner after the fit. Line L7 scores the motion by the LCP.
Lemma 1: the ratios are affine invariant
Let be an affine map with invertible. If are coplanar and the segments and meet at , then the segments and meet at , with the same and .
Proof. , because maps a weighted mean to . So lies on both image segments at the parameters and . The image lines are not parallel, because is invertible and the lines and are not parallel, so they meet in one point, which is .
A rigid motion is an affine map, so the ratios are rigid invariants too. The ratios do not determine the base up to a rigid motion: any affine image of the base has the same ratios. This is why line L6 checks the rigid fit.
Lemma 2: completeness of the extraction
Suppose is a rigid motion and contains points with , , and all at most . If , then is among the tuples of line L5.
Proof. keeps distances, so , and by the triangle inequality . So passes line L4; the same holds for with . Next, is affine, so , and
In the same way the point of the pair is within of . Since , the two points are within of each other, so line L5 keeps the tuple.
The reference code finds every such tuple, because the grid query of line L5 returns all stored points within : a point within of the query lies in one of the 27 cubes of side around the cube of the query.
Lemma 3: the true tuple passes the rigid check
Under the conditions of Lemma 2, the Kabsch fit from to has every residual at most .
Proof. The Kabsch method returns a rigid motion that minimizes the sum of squared residuals over all rigid motions. The motion has sum at most . So the fit has sum at most , and each residual is at most .
If are not on one line, which the base selection ensures, then four exact correspondences determine the rigid motion, so for the fit equals .
Theorem
If in some trial the base lies in the overlap, in the sense of Lemma 2 with , then that trial scores a motion whose residuals on the base are at most , and the result of 4PCS has an LCP score at least the score of .
Proof. Lemmas 2 and 3 show that the tuple is extracted and survives the check, so line L7 scores . The best score over all trials is kept.
What this does not prove
- The theorem needs a trial whose base lies in the overlap. The base is random, so this holds only with some probability. If a fraction of the points of lie in the overlap and the base were four independent uniform picks, the chance per trial would be about , and the number of trials for a success probability would follow the RANSAC bound. The reference code picks wide bases, which are not uniform, so this is a guide, not a bound.
- A motion with the best LCP need not be the true motion. A small , a symmetric shape or a small overlap can make a wrong motion score higher.
- The motion is fit to four points only, so its error grows with the noise and with a small base. A refinement such as ICP on all points is usual.
Complexity
The model is the real RAM. Line L2 takes time. Line L4 takes time by brute force over the pairs. Line L5 builds the grid in time linear in and finds the candidate sets with one grid query for each pair of ; when the points are spread evenly, each query looks at stored points, so the extraction takes , the bound stated in the paper. Each candidate costs for the fit and grid queries for the LCP, each when the points are spread evenly and in the worst case. So trials take time on evenly spread points and in the worst case. The space is for the pairs and the candidates.
The number depends on the data and on . With exact data and , the number of pairs at one distance is far below for points in general position, so is small; with a large or a regular shape, many pairs pass, and can be large. The number of trials follows the RANSAC bound: if a trial picks a base in the overlap with probability , then trials succeed with probability at least . A base needs only 4 points in the overlap, and wide bases are allowed, so is much larger than for methods that need more points.
Properties
- Global. The start pose does not matter.
- No features. It uses only the positions of the points, so it works on surfaces with little texture or with noisy normals.
- Randomized. The result depends on the random bases. More trials give a higher chance of success.
- Robust to partial overlap and outliers. The LCP score counts only the points that fit, and the base needs only 4 points in the overlap.
- Approximate. The motion comes from four points. A local method such as ICP usually refines it.
- Quadratic per trial. The brute force pair search costs , so the clouds are usually downsampled first.
Variants and improvements
- Faster extraction. Mellado, Aiger and Mitra (2014) find the pairs at a given distance with a spatial index instead of a scan of all pairs, and filter the pairs of pairs by the angle between the two segments, which the ratios alone do not fix. The authors report a cost per trial close to linear in plus the size of the output.
- Sampling of the score. Scoring on a random sample of and stopping a candidate early when it cannot beat the best score saves much time.
- Other bases. Later methods in the same family use bases that are not coplanar.
When to use it
Use 4PCS to align two scans with an unknown start pose when features are not reliable, for example on smooth or noisy surfaces, and when the overlap is moderate. Downsample the clouds first, for example with a voxel grid, because the cost grows as per trial, and refine the result with ICP. When good features exist, fast global registration or TEASER are usually faster. When a proof of the global optimum is needed, use Go-ICP. For recognition of many models in one scene, geometric hashing stores bases of the models in advance.
Pitfalls
- The choice of delta. must cover the noise and the sampling: two scans of the same surface do not sample the same points, so the image of a base point is only near some point of . A too small misses the true candidates; a too large one lets and the cost explode.
- Base width. A narrow base gives a poor estimate of the rotation. A base wider than the overlap cannot lie in it. The paper sets the width from an estimate of the overlap.
- Affine but not rigid. The ratios accept every affine image of the base. Check the rigid fit, or the score of many wrong candidates is wasted, and a wrong one may win on a degenerate shape.
- Mirror images. With or , both orders of a pair give the same point, which doubles the candidates.
- Flat or symmetric shapes. A plane, a sphere or a cylinder has many motions with the same LCP. No score based on point positions alone can pick the right one.
- Coplanar base in a curved scene. On a strongly curved surface, few wide quadruples are coplanar within , so base selection fails often.
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/.
"""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()
four_points_congruent_sets.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-points-congruent-sets/. The authors are listed in prov/2MMXJS.jsonl.
"""4-points congruent sets (Aiger, Mitra and Cohen-Or, SIGGRAPH 2008).
Input: two point clouds P and Q in R^3 that overlap, an error bound delta
and a number of trials. Output: a rigid motion T = (R, t) with T P close to
Q on as many points as possible: the largest common pointset (LCP) score,
the number of points p of P with a point of Q within delta of T p.
Each trial picks a wide, nearly coplanar base (a, b, c, d) from P, whose
segments ab and cd meet at a point e. The two ratios
r1 = |a - e| / |a - b| and r2 = |c - e| / |c - d| do not change under an
affine map, so they also hold for the image of the base in Q. The trial
finds all pairs of Q at the distances |a - b| and |c - d|, computes the
points that the ratios give on each pair, and matches these points. Each
match is a 4-point set of Q that is congruent to the base up to delta. The
best rigid motion from the base to each set is then scored by the LCP.
The extraction uses brute force over pairs, O(n^2) per trial, and a grid
for the matching of points, as the reference stand-in for the range search
of the paper.
"""
from __future__ import annotations
import math
import random
from typing import Dict, List, Optional, Sequence, Tuple
from cvla import det, mul, svd, transpose
Vector = List[float]
Matrix = List[List[float]]
def _sub(a, b):
return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
def _dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def _dist(a, b) -> float:
return math.sqrt(_dot(_sub(a, b), _sub(a, b)))
def _cross(a, b):
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 apply(R: Matrix, t: Sequence[float], p: Sequence[float]) -> Vector:
return [R[i][0] * p[0] + R[i][1] * p[1] + R[i][2] * p[2] + t[i] for i in range(3)]
def kabsch(A: Sequence[Sequence[float]], B: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector]:
"""The rigid motion (R, t) that minimizes sum |R a + t - b|^2, by the SVD
of the cross-covariance with the sign fix, so that det R = +1."""
n = len(A)
ca = [sum(a[i] for a in A) / n for i in range(3)]
cb = [sum(b[i] for b in B) / n for i in range(3)]
H = [[sum((a[i] - ca[i]) * (b[j] - cb[j]) for a, b in zip(A, B)) 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))
Rc = [sum(R[i][k] * ca[k] for k in range(3)) for i in range(3)]
return R, [cb[i] - Rc[i] for i in range(3)]
def base_invariants(a, b, c, d) -> Optional[Tuple[float, float, float, float, float]]:
"""For the segments ab and cd, the parameters r1, r2 of the closest
points e1 = a + r1 (b - a) and e2 = c + r2 (d - c) of the two lines, the
lengths d1 = |a - b| and d2 = |c - d|, and the gap |e1 - e2|. Returns
None if the lines are parallel or the closest points are not inside
both segments."""
u, v, w = _sub(b, a), _sub(d, c), _sub(a, c)
A, B, C = _dot(u, u), _dot(u, v), _dot(v, v)
D, E = _dot(u, w), _dot(v, w)
den = A * C - B * B
if den <= 1e-12 * A * C:
return None
r1 = (B * E - C * D) / den
r2 = (A * E - B * D) / den
if not (0.0 < r1 < 1.0 and 0.0 < r2 < 1.0):
return None
e1 = [a[i] + r1 * u[i] for i in range(3)]
e2 = [c[i] + r2 * v[i] for i in range(3)]
return r1, r2, math.sqrt(A), math.sqrt(C), _dist(e1, e2)
def select_base(P: Sequence[Sequence[float]], rng: random.Random, delta: float,
tries: int = 30, max_width: float = math.inf
) -> Optional[Tuple[Tuple[int, int, int, int], Tuple[float, float, float, float]]]:
"""A wide base: the widest of `tries` random triangles (a, b, c) with
sides at most max_width, then the point d nearest to their plane, within
max_width of a, for which one of the three pairings of the four points
into two segments gives segments that meet within delta. Returns
((ia, ib, ic, id), (r1, r2, d1, d2)) or None."""
n = len(P)
best, best_area = None, 0.0
for _ in range(tries):
i, j, k = rng.sample(range(n), 3)
if max(_dist(P[i], P[j]), _dist(P[i], P[k]), _dist(P[j], P[k])) > max_width:
continue
nrm = _cross(_sub(P[j], P[i]), _sub(P[k], P[i]))
area = math.sqrt(_dot(nrm, nrm))
if area > best_area:
best, best_area = (i, j, k), area
if best is None or best_area == 0.0:
return None
i, j, k = best
normal = _cross(_sub(P[j], P[i]), _sub(P[k], P[i]))
nn = math.sqrt(_dot(normal, normal))
order = sorted((abs(_dot(_sub(P[l], P[i]), normal)) / nn, l) for l in range(n)
if l not in best and _dist(P[l], P[i]) <= max_width)
for h, l in order:
if h > delta:
break
for ia, ib, ic, id_ in ((i, j, k, l), (i, k, j, l), (i, l, j, k)):
inv = base_invariants(P[ia], P[ib], P[ic], P[id_])
if inv is not None and inv[4] <= delta:
return (ia, ib, ic, id_), inv[:4]
return None
class Grid:
"""Points hashed into cubes of side `cell`, for radius queries with a
radius of at most `cell`."""
def __init__(self, points: Sequence[Sequence[float]], cell: float):
self.cell = cell
self.points = points
self.cells: Dict[Tuple[int, int, int], List[int]] = {}
for idx, p in enumerate(points):
self.cells.setdefault(self._key(p), []).append(idx)
def _key(self, p):
return (math.floor(p[0] / self.cell), math.floor(p[1] / self.cell), math.floor(p[2] / self.cell))
def near(self, x: Sequence[float], radius: float) -> List[int]:
kx, ky, kz = self._key(x)
r2 = radius * radius
out = []
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for dz in (-1, 0, 1):
for idx in self.cells.get((kx + dx, ky + dy, kz + dz), ()):
p = self.points[idx]
if (p[0] - x[0]) ** 2 + (p[1] - x[1]) ** 2 + (p[2] - x[2]) ** 2 <= r2:
out.append(idx)
return out
def pairs_at_distance(Q: Sequence[Sequence[float]], dist: float, eps: float) -> List[Tuple[int, int]]:
"""All ordered pairs (i, j), i != j, with | |q_i - q_j| - dist | <= eps."""
out = []
for i in range(len(Q)):
for j in range(i + 1, len(Q)):
if abs(_dist(Q[i], Q[j]) - dist) <= eps:
out.append((i, j))
out.append((j, i))
return out
def congruent_sets(Q: Sequence[Sequence[float]], r1: float, r2: float, d1: float, d2: float,
eps: float) -> List[Tuple[int, int, int, int]]:
"""All (i, j, k, l) with |q_i q_j| = d1 and |q_k q_l| = d2 up to eps and
|(q_i + r1 (q_j - q_i)) - (q_k + r2 (q_l - q_k))| <= eps."""
R1 = pairs_at_distance(Q, d1, eps) # @line L4
R2 = pairs_at_distance(Q, d2, eps)
E1 = [[Q[i][c] + r1 * (Q[j][c] - Q[i][c]) for c in range(3)] for i, j in R1]
grid = Grid(E1, max(eps, 1e-12))
out = []
for k, l in R2: # @line L5
e2 = [Q[k][c] + r2 * (Q[l][c] - Q[k][c]) for c in range(3)]
for s in grid.near(e2, eps):
i, j = R1[s]
if len({i, j, k, l}) == 4:
out.append((i, j, k, l))
return out
def lcp_score(P: Sequence[Sequence[float]], grid_q: Grid, R: Matrix, t: Sequence[float], delta: float) -> int:
"""The number of points p with a point of Q within delta of R p + t."""
return sum(1 for p in P if grid_q.near(apply(R, t, p), delta))
def four_pcs(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]], delta: float,
n_trials: int = 20, rng: Optional[random.Random] = None,
sample: Optional[int] = None, tries: int = 30,
max_width: float = math.inf) -> Dict[str, object]:
"""Align P to Q. `sample` limits the points of P used for the LCP score;
`tries` and `max_width` control the base, see select_base. Returns R,
t, the LCP score, and the number of candidate sets tried."""
rng = rng or random.Random(0)
grid_q = Grid(Q, delta)
Ps = list(P) if sample is None or sample >= len(P) else rng.sample(list(P), sample)
best = {"R": [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], "t": [0.0, 0.0, 0.0],
"score": -1, "candidates": 0}
for _ in range(n_trials): # @line L1
found = select_base(P, rng, delta, tries, max_width) # @line L2
if found is None:
continue
base, (r1, r2, d1, d2) = found # @line L3
for i, j, k, l in congruent_sets(Q, r1, r2, d1, d2, delta):
best["candidates"] += 1
R, t = kabsch([P[x] for x in base], [Q[i], Q[j], Q[k], Q[l]]) # @line L6
if max(_dist(apply(R, t, P[x]), Q[y]) for x, y in zip(base, (i, j, k, l))) > 2.0 * delta:
continue
score = lcp_score(Ps, grid_q, R, t, delta) # @line L7
if score > best["score"]:
best.update(R=R, t=t, score=score)
return best # @line L8
test_four_points_congruent_sets.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-points-congruent-sets/. The authors are listed in prov/2MMXJS.jsonl.
import itertools
import math
import random
import unittest
from cvla import det, mul, transpose
from four_points_congruent_sets import (Grid, apply, base_invariants, congruent_sets, four_pcs,
kabsch, lcp_score, pairs_at_distance, select_base)
def random_rotation(rng):
q = [rng.gauss(0.0, 1.0) for _ in range(4)]
n = math.sqrt(sum(v * v for v in q))
w, x, y, z = (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 rot_angle(R1, R2):
m = mul(transpose(R1), R2)
c = max(-1.0, min(1.0, (m[0][0] + m[1][1] + m[2][2] - 1.0) / 2.0))
return math.acos(c)
def surface(rng, n, x0=-1.0, x1=1.0):
pts = []
for _ in range(n):
x, y = rng.uniform(x0, x1), rng.uniform(-1.0, 1.0)
pts.append([x, y, 0.3 * x * y + 0.2 * x * x - 0.1 * y])
return pts
EXAMPLE_P = [[0.0, 0.0, 0.0], [4.0, 2.0, 0.0], [0.0, 3.0, 0.0], [3.0, 0.0, 0.0],
[1.0, 1.0, 2.0], [3.0, 3.0, 1.0], [-1.0, 2.0, 1.0], [2.0, -1.0, 2.0]]
class TestInvariants(unittest.TestCase):
def test_example_base(self):
r1, r2, d1, d2, gap = base_invariants(*EXAMPLE_P[:4])
self.assertAlmostEqual(r1, 0.5)
self.assertAlmostEqual(r2, 2.0 / 3.0)
self.assertAlmostEqual(d1, math.sqrt(20.0))
self.assertAlmostEqual(d2, math.sqrt(18.0))
self.assertAlmostEqual(gap, 0.0)
def test_ratios_are_affine_invariant(self):
rng = random.Random(1)
for _ in range(50):
a, b = [rng.uniform(-1, 1) for _ in range(3)], [rng.uniform(-1, 1) for _ in range(3)]
c = [rng.uniform(-1, 1) for _ in range(3)]
s, u = rng.uniform(0.1, 0.9), rng.uniform(0.1, 0.9)
e = [a[i] + s * (b[i] - a[i]) for i in range(3)]
d = [c[i] + (e[i] - c[i]) / u for i in range(3)] # so that e = c + u (d - c)
M = [[rng.uniform(-2, 2) for _ in range(3)] for _ in range(3)]
if abs(det(M)) < 0.1:
continue
tt = [rng.uniform(-1, 1) for _ in range(3)]
img = [apply(M, tt, p) for p in (a, b, c, d)]
for pts in ((a, b, c, d), img):
inv = base_invariants(*pts)
self.assertIsNotNone(inv)
self.assertAlmostEqual(inv[0], s, places=8)
self.assertAlmostEqual(inv[1], u, places=8)
self.assertLess(inv[4], 1e-8)
def test_segments_that_miss(self):
self.assertIsNone(base_invariants([0, 0, 0], [1, 0, 0], [2, 1, 0], [2, -1, 0]))
self.assertIsNone(base_invariants([0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]))
class TestSearch(unittest.TestCase):
def test_pairs_at_distance(self):
rng = random.Random(2)
Q = [[rng.uniform(0, 1) for _ in range(3)] for _ in range(30)]
got = set(pairs_at_distance(Q, 0.5, 0.05))
want = {(i, j) for i, j in itertools.permutations(range(30), 2)
if abs(math.dist(Q[i], Q[j]) - 0.5) <= 0.05}
self.assertEqual(got, want)
def test_example_congruent_sets(self):
R = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
Q = [apply(R, [5.0, 0.0, 1.0], p) for p in EXAMPLE_P] + [[0.0, 0.0, 0.0], [6.0, 4.0, 1.0]]
cands = congruent_sets(Q, 0.5, 2.0 / 3.0, math.sqrt(20.0), math.sqrt(18.0), 0.01)
self.assertEqual(sorted(cands), [(0, 1, 2, 3), (1, 0, 2, 3)])
Rk, tk = kabsch(EXAMPLE_P[:4], [Q[i] for i in (0, 1, 2, 3)])
self.assertLess(rot_angle(R, Rk), 1e-9)
self.assertEqual(lcp_score(EXAMPLE_P, Grid(Q, 0.01), Rk, tk, 0.01), 8)
Rk, tk = kabsch(EXAMPLE_P[:4], [Q[i] for i in (1, 0, 2, 3)])
self.assertEqual(lcp_score(EXAMPLE_P, Grid(Q, 0.01), Rk, tk, 0.01), 0)
def test_true_image_of_base_is_found(self):
rng = random.Random(3)
P = surface(rng, 80)
R, t = random_rotation(rng), [rng.uniform(-1, 1) for _ in range(3)]
Q = [apply(R, t, p) for p in P]
found = select_base(P, rng, 0.02)
self.assertIsNotNone(found)
base, (r1, r2, d1, d2) = found
self.assertIn(base, congruent_sets(Q, r1, r2, d1, d2, 0.02))
def test_grid_matches_brute_force(self):
rng = random.Random(4)
pts = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(200)]
g = Grid(pts, 0.2)
for _ in range(30):
x = [rng.uniform(-1, 1) for _ in range(3)]
want = sorted(i for i, p in enumerate(pts) if math.dist(p, x) <= 0.15)
self.assertEqual(sorted(g.near(x, 0.15)), want)
class TestKabsch(unittest.TestCase):
def test_exact_and_proper(self):
rng = random.Random(5)
R, t = random_rotation(rng), [1.0, -2.0, 0.5]
A = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(4)]
Rk, tk = kabsch(A, [apply(R, t, a) for a in A])
self.assertLess(rot_angle(R, Rk), 1e-9)
self.assertAlmostEqual(det(Rk), 1.0, places=12)
for x, y in zip(tk, t):
self.assertAlmostEqual(x, y, places=9)
class TestFourPCS(unittest.TestCase):
def test_full_overlap_with_noise_and_outliers(self):
rng = random.Random(6)
P = surface(rng, 80)
R, t = random_rotation(rng), [rng.uniform(-1, 1) for _ in range(3)]
Q = [[v + rng.gauss(0.0, 0.003) for v in apply(R, t, p)] for p in P]
Q += [[rng.uniform(-2, 2) for _ in range(3)] for _ in range(20)]
rng.shuffle(Q)
out = four_pcs(P, Q, 0.03, n_trials=3, rng=random.Random(7))
self.assertLess(rot_angle(R, out["R"]), math.radians(2.0))
self.assertGreaterEqual(out["score"], 76)
def test_partial_overlap(self):
rng = random.Random(8)
S = surface(rng, 90)
P = [p for p in S if p[0] < 0.4]
R, t = random_rotation(rng), [rng.uniform(-1, 1) for _ in range(3)]
Q = [[v + rng.gauss(0.0, 0.003) for v in apply(R, t, p)] for p in S if p[0] > -0.4]
out = four_pcs(P, Q, 0.03, n_trials=40, rng=random.Random(9), tries=5, max_width=0.8)
self.assertLess(rot_angle(R, out["R"]), math.radians(3.0))
if __name__ == "__main__":
unittest.main()
History
Aiger, Mitra and Cohen-Or presented 4PCS at SIGGRAPH 2008. It belongs to a long line of methods that align shapes by matching small sets of points, from RANSAC and the alignment method of object recognition to geometric hashing. The key step of 4PCS is the use of affine invariant ratios, which lets it extract all congruent 4-point sets from the pairs of points, instead of trying all 4-tuples. Mellado, Aiger and Mitra (2014) gave a much faster way to extract these sets, which made the method practical on large scans. Open source versions of 4PCS and its faster forms exist, and they are a common first step of scan registration before ICP.
References
- Dror Aiger, Niloy J. Mitra and Daniel Cohen-Or, 4-points congruent sets for robust pairwise surface registration, ACM Transactions on Graphics 27(3), Article 85, 2008 (SIGGRAPH 2008), The affine invariant ratios of a coplanar four-point base, the extraction of the congruent sets from the pairs at the two base distances, the largest common pointset score, the number of trials, and the experiments on scans with noise, outliers and partial overlap
- Shinji Umeyama, Least-squares estimation of transformation parameters between two point patterns, IEEE Transactions on Pattern Analysis and Machine Intelligence 13(4), 1991, 376-380, The best rigid motion between point sets by the SVD with the sign fix, used to fit each candidate set
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 2MMXJS Edit this page History Report an error Markdown