Algorithmcore
Linear triangulation
Also called DLT triangulation, homogeneous triangulation.
Stack the cross product equations x × PX = 0 of all views and take X as the singular vector of least singular value.
- Solves
- Point triangulation
- Time
- Θ(m) worst · average · best
- Space
- Θ(m) extra
- Where
- m = the number of views, at least 2
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Richard Hartley, Peter Sturm, 1997
Linear triangulation finds a 3D point from its images in two or more views with known camera matrices. Each view says that the image point and the projection are the same point of the image, so their cross product is zero. That gives two independent linear equations in the homogeneous point . The equations of all views form a system with a matrix. On exact data has rank 3, and is its null vector. On noisy data the method takes the unit vector that minimizes , the right singular vector of the smallest singular value. This is the direct linear transformation (DLT) idea, the same one used for camera resectioning. It is fast and works for any number of views, but the quantity it minimizes has no geometric meaning. It is the usual first step before optimal triangulation or bundle adjustment.
In plain words
Each photo of a point tells you a line in space on which the point must lie: the line from the camera through the dot in the photo. With two or more photos, the point is where these lines meet. The method writes "the point lies on this line" as two simple equations for each photo, puts all equations in one table, and asks for the point that comes closest to satisfying all of them. A standard matrix tool answers this in one step. When the photos are perfect, the answer is exact. When the dots are a little off, the lines do not meet, and the answer is a good guess, but not the best possible one.
The problem
Input. Camera matrices , , each , and image points in the same units as (pixels for ).
Output. A 3D point . If the image points are exact images of a finite point that is not on the line through two of the centers, the output is that point.
The algorithm
Write for row of . The cross product , with , has three entries, of which two are independent:
LINEAR-TRIANGULATION(P_1 .. P_m, x_1 .. x_m)- 1
A <- an empty matrix with 4 columns - 2
for each view i, with x_i = (u_i, v_i) - 3
append the rows u_i p_i^3T - p_i^1T and v_i p_i^3T - p_i^2T to A - 4
X <- the unit vector that minimizes || A X ||, the last right singular vector of A - 5
if X_4 = 0 then report a point at infinity - 6
return (X_1, X_2, X_3) / X_4
The inhomogeneous variant sets and solves the linear least squares problem , where is the first three columns of and the last one. The code on this page has both. On exact data they give the same point.
Example
Take and , two cameras with and centers and . The point has the images and .
| line | value |
|---|---|
| L3, view 1 | rows and |
| L3, view 2 | rows and |
| L4 | singular values , , , ; null vector |
| L6 |
Now move the second image point to , so that the two rays no longer meet. The smallest singular value becomes , and line L6 gives . The inhomogeneous variant gives , a different point. If the world origin is moved by 10 along the axis and the cameras are changed to match, the inhomogeneous result moves with it, but the homogeneous result changes to in the old frame.
Correctness
For one view, the two rows vanish exactly on the vectors with a multiple of . Because has rank 3, this set is the 2-dimensional subspace spanned by the camera center and : the back-projected ray. Two such subspaces with independent , , meet only in the multiples of . So on exact data the null space of is spanned by , the smallest singular value is 0 and simple, and line L4 returns . The full proof, with the inhomogeneous variant and the invariance facts, is in the proof file of this page.
Proof: On exact data the DLT matrix has rank 3 and its null vector is the point, unless the point lies on the line through two centersfull
We use the notation of the page. Each view has a camera matrix of rank 3 with rows , , and center , the nonzero vector with . The image point is , and . The matrix has the rows and for all . The arithmetic is exact (real RAM).
Claim. Let be a homogeneous point with and for every (exact data, point in front of or behind the cameras, but not at a center). Assume that two of the cameras, say 1 and 2, have different centers, and that is not on the line through them, that is, , and are linearly independent. Then (a) the null space of is spanned by , so has rank 3; (b) the homogeneous method returns the point ; (c) the inhomogeneous method returns the same point.
Lemma 1 (the two rows of one view). For one view, a vector satisfies both of its rows, and , if and only if is a multiple of , possibly the zero multiple.
Proof. Put , the third entry of . The two equations say and , so together they say . Conversely, if , the third entry gives , and the first two entries are the two equations.
Lemma 2 (the ray as a plane through the origin of ). If with , then the vectors that satisfy the two rows of the view form the 2-dimensional subspace .
Proof. By Lemma 1 the set is , the preimage of a line through the origin of . The map has rank 3, so it is onto and its kernel is . The preimage of a 1-dimensional subspace under an onto map with a 1-dimensional kernel has dimension 2. It contains and , which are independent because , so it equals .
Proof of part (a). is not a center, so for every . By Lemma 2 the null space of is the intersection of the subspaces . It contains . Let be in the intersection of the first two: . Then , and the independence of , , gives , so . Further views can only make the intersection smaller, and it always contains . So the null space is , and , with 4 columns, has rank 3.
Proof of part (b). Line L4 returns a unit vector that minimizes , the right singular vector of the smallest singular value. By part (a) the smallest singular value is 0 and it is simple, so the minimizers are exactly . Both have a nonzero fourth entry, so line L5 does not stop, and line L6 returns .
Proof of part (c). Write with the first three columns. The inhomogeneous method minimizes over . If for some , then is in the null space of , which is impossible by part (a), because every nonzero vector of has a nonzero fourth entry. So has full column rank, is invertible, and the minimizer is unique. The vector gives , so it is the minimizer.
Remark (invariance under a change of the world frame). Replace the world frame by with an invertible matrix ; the cameras become and the matrix becomes . For the inhomogeneous method let be affine, with last row . Then maps the vectors with last entry 1 onto themselves, and , so the minimizer moves with the frame: the method is affine invariant, also on noisy data. For the homogeneous method let with orthogonal and . For we have and , so , the minimizers correspond, and the method is invariant under such , for example a rotation of the world about its origin. A translation is not of this form, and on noisy data the homogeneous result changes when the world origin moves; the example of the page shows this. On exact data both methods return the true point in every frame, by parts (b) and (c).
Complexity
Building takes time. The SVD of a matrix costs per sweep of a Jacobi method, and a fixed number of sweeps is enough in practice; with formed first, the work is plus the eigenvectors of one matrix. The extra space is for , or if only is kept. In the real RAM model the SVD of a fixed number of columns counts as .
Properties
- Exact on exact data. The true point is the null vector whenever the rays meet at one finite point, off the line through two centers.
- Any number of views. Each view adds two rows; more views reduce the effect of noise.
- Not projective invariant. The homogeneous method depends on the choice of the world frame. It is invariant under rotations of the world about its origin, but not under translations.
- Affine invariant variant. The inhomogeneous method gives the same point after any affine change of the world frame. It cannot represent a point at infinity.
- Algebraic error. The minimized quantity is an algebraic error, not the reprojection error, so the result is not the maximum likelihood estimate under Gaussian noise.
Variants and improvements
- Normalized coordinates. Run the method on with , or apply Hartley normalization to the image points. This improves the conditioning of when the inputs are in pixels.
- Row weights. Dividing the two rows of a view by the depth of the current estimate and solving again turns the algebraic error into the reprojection error step by step; this is an iteratively reweighted form of the method.
- Optimal two-view method. Optimal triangulation corrects the two image points first and then triangulates exactly; it minimizes the reprojection error.
- Midpoint. The midpoint method works in a Euclidean frame and takes the point closest to the rays.
- Refinement. A few Gauss-Newton steps on the reprojection error, starting from the linear result, give the maximum likelihood estimate in most cases.
When to use it
Use it as the default first estimate of a point in structure from motion, both for two views and for many, when the cameras are known. In a projective reconstruction, where there is no Euclidean frame, it is the natural choice. When accuracy matters, refine the result on the reprojection error, either point by point or in a full bundle adjustment.
Pitfalls
- Pixels with a large offset. With and near 1000, the rows of have entries of very different size. Normalize the image points first.
- Points at infinity. Far points or nearly parallel rays give close to 0; dividing by it gives very large coordinates. Keep the homogeneous vector, or reject the point.
- Small baseline. When the angle between the rays is small, the depth is poorly fixed; the smallest two singular values of come close.
- No cheirality check. The method can return a point behind a camera. Check the sign of the depth in each view with the cheirality test.
- Treating it as optimal. Its result differs from the minimum of the reprojection error under noise, and the difference depends on the world frame.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Camera geometry and synthetic scenes for the computer vision pages.
Conventions (prompts of the area, also stated on the pages):
- The camera frame has X to the right, Y down and Z forward. A point is in
front of the camera if Z > 0.
- K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]] in pixels.
- A world point Xw maps to the camera frame by Xc = R Xw + t. The camera
matrix is P = K [R | t], and the center is C = -R^T t.
- Rotations are active and right-handed. Quaternions are (w, x, y, z) in the
Hamilton convention.
This module holds no algorithm of a computer vision page.
"""
from __future__ import annotations
import math
import random
from typing import Dict, List, Optional, Sequence, Tuple
from cvla import det, matvec, mul, solve, transpose
Matrix = List[List[float]]
Vector = List[float]
def to_h(x: Sequence[float]) -> Vector:
"""Append a 1: the homogeneous vector of a point."""
return [float(v) for v in x] + [1.0]
def from_h(x: Sequence[float]) -> Vector:
"""Divide by the last entry and drop it. Raises ValueError if the last
entry is zero (a point at infinity)."""
w = x[-1]
if w == 0:
raise ValueError("from_h: point at infinity")
return [v / w for v in x[:-1]]
def make_K(fx: float, fy: float, cx: float, cy: float, s: float = 0.0) -> Matrix:
"""The intrinsic matrix [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
return [[float(fx), float(s), float(cx)],
[0.0, float(fy), float(cy)],
[0.0, 0.0, 1.0]]
def camera_matrix(K: Sequence[Sequence[float]], R: Sequence[Sequence[float]],
t: Sequence[float]) -> Matrix:
"""The 3 x 4 camera matrix P = K [R | t]."""
rt = [list(R[i]) + [t[i]] for i in range(3)]
return mul(K, rt)
def project(P: Sequence[Sequence[float]], X):
"""Pixel coordinates (u, v) of a point X under the camera P.
X is a 3D point (3 entries) or a homogeneous point (4 entries). If X is
a list of points, the result is the list of their projections."""
if len(X) > 0 and isinstance(X[0], (list, tuple)):
return [project(P, x) for x in X]
xh = to_h(X) if len(X) == 3 else list(X)
return from_h(matvec(P, xh))
def camera_center(P: Sequence[Sequence[float]]) -> Vector:
"""The center C of a finite camera P = [M | p4]: C = -M^-1 p4, so that
P (C, 1) = 0."""
m = [list(row[:3]) for row in P]
p4 = [row[3] for row in P]
return [-v for v in solve(m, p4)]
def rot_x(a: float) -> Matrix:
"""Rotation by the angle a (radians) about the X axis."""
c, s = math.cos(a), math.sin(a)
return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
def rot_y(a: float) -> Matrix:
"""Rotation by the angle a (radians) about the Y axis."""
c, s = math.cos(a), math.sin(a)
return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
def rot_z(a: float) -> Matrix:
"""Rotation by the angle a (radians) about the Z axis."""
c, s = math.cos(a), math.sin(a)
return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
def axis_angle_to_R(axis: Sequence[float], theta: Optional[float] = None) -> Matrix:
"""Rotation by theta (radians) about the axis, by the right-hand rule
(Rodrigues formula). The axis need not be a unit vector. If theta is
None, axis is the rotation vector w = theta a, with theta = ||w||."""
n = math.sqrt(sum(float(v) * float(v) for v in axis))
if theta is None:
theta = n
if n == 0.0 or theta == 0.0:
return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
x, y, z = (float(v) / n for v in axis)
c, s = math.cos(theta), math.sin(theta)
d = 1.0 - c
return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
[y * x * d + z * s, c + y * y * d, y * z * d - x * s],
[z * x * d - y * s, z * y * d + x * s, c + z * z * d]]
def quat_to_R(q: Sequence[float]) -> Matrix:
"""Rotation matrix of the quaternion q = (w, x, y, z), Hamilton
convention. q is normalized first; q and -q give the same matrix."""
n = math.sqrt(sum(float(v) * float(v) for v in q))
if n == 0.0:
raise ValueError("quat_to_R: zero quaternion")
w, x, y, z = (float(v) / n for v in q)
return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]
def random_rotation(rng: random.Random) -> Matrix:
"""A rotation drawn from the uniform (Haar) distribution: a uniform
random unit quaternion by the method of Shoemake (1992)."""
u1, u2, u3 = rng.random(), rng.random(), rng.random()
a, b = math.sqrt(1.0 - u1), math.sqrt(u1)
q = (b * math.cos(2 * math.pi * u3), a * math.sin(2 * math.pi * u2),
a * math.cos(2 * math.pi * u2), b * math.sin(2 * math.pi * u3))
return quat_to_R(q)
def _small_rotation(rng: random.Random, max_angle: float) -> Matrix:
axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
return axis_angle_to_R(axis, rng.uniform(0.0, max_angle))
def random_scene(rng: random.Random, n: int = 20, n_cams: int = 2,
K: Optional[Sequence[Sequence[float]]] = None,
cams: Optional[Sequence[Tuple]] = None,
radius: float = 1.0, distance: float = 5.0,
max_angle: float = 0.3, planar: bool = False,
first_identity: bool = False,
size: Optional[Tuple[float, float]] = None,
min_depth: float = 0.1) -> Dict[str, list]:
"""A synthetic scene with known cameras and points.
Cameras: if cams is given, it is a list of (K, R, t) and is used as it
is. Otherwise n_cams cameras look at the world origin from the distance
`distance`. Each one is the camera at center (0, 0, -distance) with
R = I, turned about the origin by a random rotation of angle at most
max_angle (radians). K defaults to make_K(800, 800, 320, 240). With
first_identity, the world frame is moved to the frame of camera 0, so
that camera 0 has R = I and t = 0 (the points move with it).
Points: n points drawn uniformly in the cube [-radius, radius]^3 (with
Z = 0 if planar, before any move of the world frame). A point is kept
only if its depth is at least min_depth in every camera, and, if size =
(W, H) is given, if its projection lies in [0, W] x [0, H] in every
camera. Raises ValueError if 1000 n draws are not enough.
Returns a dict with lists "K", "R", "t", "P" (one entry per camera),
"X" (the 3D points) and "x" (x[i][j] is the pixel of point j in
camera i, without noise)."""
if cams is not None:
Ks = [[list(r) for r in c[0]] for c in cams]
Rs = [[list(r) for r in c[1]] for c in cams]
ts = [list(c[2]) for c in cams]
else:
k0 = [list(r) for r in K] if K is not None else make_K(800, 800, 320, 240)
Ks, Rs, ts = [], [], []
c0 = [0.0, 0.0, -float(distance)]
for _ in range(n_cams):
q = _small_rotation(rng, max_angle)
r = transpose(q)
center = matvec(q, c0)
Ks.append([list(row) for row in k0])
Rs.append(r)
ts.append([-v for v in matvec(r, center)])
pts: List[Vector] = []
tries = 0
while len(pts) < n:
tries += 1
if tries > 1000 * max(n, 1):
raise ValueError("random_scene: cannot place the points")
x = [rng.uniform(-radius, radius) for _ in range(3)]
if planar:
x[2] = 0.0
ok = True
for k, r, t in zip(Ks, Rs, ts):
xc = [a + b for a, b in zip(matvec(r, x), t)]
if xc[2] < min_depth:
ok = False
break
if size is not None:
u = (k[0][0] * xc[0] + k[0][1] * xc[1]) / xc[2] + k[0][2]
v = k[1][1] * xc[1] / xc[2] + k[1][2]
if not (0.0 <= u <= size[0] and 0.0 <= v <= size[1]):
ok = False
break
if ok:
pts.append(x)
if first_identity and Rs:
r0, t0 = Rs[0], ts[0]
pts = [[a + b for a, b in zip(matvec(r0, x), t0)] for x in pts]
r0t = transpose(r0)
newR, newt = [], []
for r, t in zip(Rs, ts):
rr = mul(r, r0t)
newR.append(rr)
newt.append([a - b for a, b in zip(t, matvec(rr, t0))])
Rs, ts = newR, newt
Rs[0] = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
ts[0] = [0.0, 0.0, 0.0]
Ps = [camera_matrix(k, r, t) for k, r, t in zip(Ks, Rs, ts)]
xs = [[project(p, x) for x in pts] for p in Ps]
return {"K": Ks, "R": Rs, "t": ts, "P": Ps, "X": pts, "x": xs}
def add_noise(rng: random.Random, pts: Sequence[Sequence[float]], sigma: float) -> List[Vector]:
"""A copy of the points with independent Gaussian noise of standard
deviation sigma added to every coordinate."""
return [[float(v) + rng.gauss(0.0, sigma) for v in p] for p in pts]
def self_test() -> None:
"""Check random_scene and quat_to_R. Raises AssertionError."""
rng = random.Random(11)
scene = random_scene(rng, n=30, n_cams=4)
for r, t in zip(scene["R"], scene["t"]):
for x in scene["X"]:
assert matvec(r, x)[2] + t[2] > 0.0
for _ in range(5):
q = [rng.gauss(0.0, 1.0) for _ in range(4)]
r = quat_to_R(q)
rtr = mul(transpose(r), r)
assert all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) <= 1e-12
for i in range(3) for j in range(3))
assert abs(det(r) - 1.0) <= 1e-12
if __name__ == "__main__":
self_test()
cvla.py 494 lines
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.
A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.
Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
1e-8.
This module holds no algorithm of a computer vision page.
"""
from __future__ import annotations
import cmath
import math
from typing import List, Sequence, Tuple
Matrix = List[List[float]]
Vector = List[float]
_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100
# ---------------------------------------------------------------- basics
def zeros(m: int, n: int) -> Matrix:
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n: int) -> Matrix:
"""The n x n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a) -> bool:
return len(a) > 0 and isinstance(a[0], (list, tuple))
def transpose(a: Sequence[Sequence[float]]) -> Matrix:
"""The transpose of a matrix."""
return [list(col) for col in zip(*a)]
def add(a, b):
"""a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, c):
"""c times a, for a vector or a matrix a and a number c."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
"""The matrix product a b."""
if len(a[0]) != len(b):
raise ValueError("mul: shapes do not match")
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
"""The product a x of a matrix and a vector."""
if len(a[0]) != len(x):
raise ValueError("matvec: shapes do not match")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x: Sequence[float], y: Sequence[float]) -> float:
"""The inner product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(a) -> float:
"""The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
if _is_matrix(a):
return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
return math.sqrt(sum(float(x) * float(x) for x in a))
def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
"""The cross product a x b of two 3-vectors."""
return [a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]]
def skew(a: Sequence[float]) -> Matrix:
"""The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
z = a[0] - a[0]
return [[z, -a[2], a[1]],
[a[2], z, -a[0]],
[-a[1], a[0], z]]
# ---------------------------------------------------- Gaussian elimination
def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
"""Reduce [a | b] to upper triangular form with partial pivoting.
Works in place on copies made by the caller. Returns a, b and the sign
of the row permutation.
"""
n = len(a)
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("singular matrix")
if p != k:
a[k], a[p] = a[p], a[k]
b[k], b[p] = b[p], b[k]
sign = -sign
piv = a[k][k]
for i in range(k + 1, n):
f = a[i][k] / piv
if f == 0:
continue
ai, ak = a[i], a[k]
for j in range(k, n):
ai[j] = ai[j] - f * ak[j]
bi, bk = b[i], b[k]
for j in range(len(bi)):
bi[j] = bi[j] - f * bk[j]
return a, b, sign
def solve(a: Sequence[Sequence[float]], b):
"""Solve a x = b for a square a, by Gaussian elimination with partial
pivoting. b is a vector or a matrix (several right-hand sides); the
result has the same form. Raises ValueError on an exact zero pivot."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("solve: matrix is not square")
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
if len(rhs) != n:
raise ValueError("solve: shapes do not match")
u, c, _ = _eliminate([list(row) for row in a], rhs)
m = len(c[0]) if n else 0
x = [[0.0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = c[i][j]
for k in range(i + 1, n):
s = s - u[i][k] * x[k][j]
x[i][j] = s / u[i][i]
return [row[0] for row in x] if vec else x
def inv(a: Sequence[Sequence[float]]) -> Matrix:
"""The inverse of a square matrix. Raises ValueError if it is singular."""
n = len(a)
one = a[0][0] - a[0][0] + 1 if n else 1.0
ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
return solve(a, ident)
def det(a: Sequence[Sequence[float]]) -> float:
"""The determinant of a square matrix, by Gaussian elimination."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("det: matrix is not square")
if n == 0:
return 1.0
try:
u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
except ValueError:
return a[0][0] - a[0][0]
d = u[0][0] - u[0][0] + sign
for i in range(n):
d = d * u[i][i]
return d
# ------------------------------------------------------- Jacobi methods
def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
"""Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
a is read (the lower triangle is taken as its mirror)."""
n = len(a)
s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
v = eye(n)
for _ in range(_MAX_SWEEPS):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
apq = s[p][q]
if apq == 0.0:
continue
app, aqq = s[p][p], s[q][q]
if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
abs(apq) < 1e-300:
s[p][q] = s[q][p] = 0.0
continue
rotated = True
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(n):
skp, skq = s[k][p], s[k][q]
s[k][p] = c * skp - sn * skq
s[k][q] = sn * skp + c * skq
for k in range(n):
spk, sqk = s[p][k], s[q][k]
s[p][k] = c * spk - sn * sqk
s[q][k] = sn * spk + c * sqk
s[p][q] = s[q][p] = 0.0
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
if not rotated:
break
order = sorted(range(n), key=lambda i: s[i][i])
w = [s[i][i] for i in order]
vs = [[v[k][i] for i in order] for k in range(n)]
return w, vs
def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
"""Replace the columns with index in need by unit vectors orthogonal to
all other columns (Gram-Schmidt on the standard basis)."""
keep = [c for i, c in enumerate(cols) if i not in need]
for i in need:
best, best_norm = None, -1.0
for e in range(m):
x = [0.0] * m
x[e] = 1.0
for _ in range(2):
for c in keep:
d = dot(c, x)
x = [xi - d * ci for xi, ci in zip(x, c)]
nx = norm(x)
if nx > best_norm:
best, best_norm = x, nx
u = [xi / best_norm for xi in best]
cols[i] = u
keep.append(u)
def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
m, n = len(a), len(a[0])
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(_MAX_SWEEPS):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
cp, cq = cols[p], cols[q]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cq)
gamma = sum(x * y for x, y in zip(cp, cq))
if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
continue
rotated = True
zeta = (beta - alpha) / (2.0 * gamma)
t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
c = 1.0 / math.sqrt(1.0 + t * t)
s = c * t
cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
vp, vq = vcols[p], vcols[q]
vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
if not rotated:
break
sv = [norm(c) for c in cols]
order = sorted(range(n), key=lambda i: -sv[i])
sv = [sv[i] for i in order]
cols = [cols[i] for i in order]
vcols = [vcols[i] for i in order]
smax = sv[0] if sv else 0.0
ucols: List[Vector] = []
need: List[int] = []
for i, c in enumerate(cols):
if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
ucols.append([x / sv[i] for x in c])
else:
ucols.append([0.0] * m)
need.append(i)
if need:
_complete_basis(ucols, m, need)
return transpose(ucols), sv, transpose(vcols)
def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
"""Thin singular value decomposition by the one-sided Jacobi method.
For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
size m x k, S a list of k values in descending order and V of size
n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
For m >= n, V is square (n x n)."""
m, n = len(a), len(a[0])
if m >= n:
return _svd_tall(a)
u, s, v = _svd_tall(transpose(a))
return v, s, u
def nullvec(a: Sequence[Sequence[float]]) -> Vector:
"""A unit vector x that minimizes ||a x||: the right singular vector of
the smallest singular value. If a has fewer rows than columns, zero rows
are added first, so the result is in the null space. The sign is not
fixed."""
m, n = len(a), len(a[0])
rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
_, _, v = _svd_tall(rows)
return [v[i][n - 1] for i in range(n)]
# ---------------------------------------------- orthogonal factorizations
def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
"""QR factorization by Householder reflections. For an m x n matrix a,
returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
m, n = len(a), len(a[0])
r = [[float(x) for x in row] for row in a]
q = eye(m)
for k in range(min(m - 1, n)):
x = [r[i][k] for i in range(k, m)]
nx = norm(x)
if nx == 0.0:
continue
alpha = -nx if x[0] >= 0 else nx
v = list(x)
v[0] -= alpha
nv = norm(v)
if nv == 0.0:
continue
v = [vi / nv for vi in v]
for j in range(n):
d = sum(v[i - k] * r[i][j] for i in range(k, m))
if d != 0.0:
for i in range(k, m):
r[i][j] -= 2.0 * v[i - k] * d
for i in range(m):
d = sum(q[i][l] * v[l - k] for l in range(k, m))
if d != 0.0:
for l in range(k, m):
q[i][l] -= 2.0 * d * v[l - k]
for k in range(min(m, n)):
if r[k][k] < 0:
r[k] = [-x for x in r[k]]
for i in range(m):
q[i][k] = -q[i][k]
for i in range(m):
for j in range(min(i, n)):
r[i][j] = 0.0
return q, r
def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
"""RQ factorization of a square matrix: returns R (upper triangular,
with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
from the QR factorization of the transpose of the row-reversed matrix."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("rq: matrix is not square")
flipped = transpose([list(row) for row in reversed(a)])
q1, r1 = qr(flipped)
rt = transpose(r1)
r = [list(reversed(row)) for row in reversed(rt)]
q = [list(row) for row in reversed(transpose(q1))]
return r, q
def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
"""The lower triangular L with a = L L^T, for a symmetric positive
definite a. Raises ValueError if a pivot is not positive."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
if d <= 0:
raise ValueError("cholesky: matrix is not positive definite")
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
return low
# ---------------------------------------------------------- polynomials
def _horner(c: Sequence[complex], x):
p = 0.0
for ci in c:
p = p * x + ci
return p
def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
"""Real roots of the polynomial with the given coefficients, highest
power first. All complex roots are found by the Durand-Kerner method.
A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
part is then polished by Newton steps on the real polynomial. Returns
the real roots in ascending order, with repeats for multiple roots."""
c = [float(x) for x in coeffs]
while c and c[0] == 0.0:
c.pop(0)
n = len(c) - 1
if n < 1:
return []
c = [x / c[0] for x in c]
rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
if rho == 0.0:
return [0.0] * n
z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
for _ in range(2000):
moved = 0.0
for k in range(n):
den = 1.0 + 0j
for j in range(n):
if j != k:
den *= z[k] - z[j]
if den == 0:
den = 1e-12 * rho
step = _horner(c, z[k]) / den
z[k] -= step
moved = max(moved, abs(step) / max(1.0, abs(z[k])))
if moved <= 1e-15:
break
deriv = [c[i] * (n - i) for i in range(n)]
roots = []
for zk in z:
if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
continue
x = zk.real
px = _horner(c, x)
for _ in range(8):
dp = _horner(deriv, x)
if dp == 0.0 or px == 0.0:
break
xn = x - px / dp
pn = _horner(c, xn)
if abs(pn) >= abs(px):
break
x, px = xn, pn
roots.append(x)
return sorted(roots)
# ------------------------------------------------------------ self-test
def self_test() -> None:
"""Check svd, sym_eig and polyroots_real. Raises AssertionError."""
import random
rng = random.Random(7)
for _ in range(3):
a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
u, s, v = svd(a)
rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
assert norm(sub(rec, a)) <= 1e-10
assert all(s[i] >= s[i + 1] for i in range(4))
sym = add(a, transpose(a))
w, vv = sym_eig(sym)
rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
assert norm(sub(rec, sym)) <= 1e-10
assert all(w[i] <= w[i + 1] for i in range(4))
r = polyroots_real([1.0, -6.0, 11.0, -6.0])
assert len(r) == 3
assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))
if __name__ == "__main__":
self_test()
linear_triangulation.py 65 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-triangulation/. The authors are listed in prov/8H0B6Z.jsonl.
"""Linear (DLT) triangulation of a point from two or more views.
Each view i has a 3 x 4 camera matrix P_i with rows p1, p2, p3 and an image
point x_i = (u, v) in the same units as P_i (pixels for P = K [R | t]).
The equation x_i ~ P_i X gives two linear equations in the homogeneous
point X:
(u p3 - p1) . X = 0, (v p3 - p2) . X = 0.
The homogeneous method takes the unit X that minimizes ||A X|| (the last
right singular vector of the 2m x 4 matrix A). The inhomogeneous method
puts X = (x, y, z, 1) and solves the 2m x 3 linear least squares problem.
Cost: Theta(m) to build A and Theta(m) for the SVD of a 2m x 4 matrix (the
work per Jacobi sweep is linear in the number of rows).
"""
from __future__ import annotations
from typing import List, Sequence
from cvla import mul, nullvec, solve, transpose
Matrix = List[List[float]]
Vector = List[float]
def dlt_rows(Ps: Sequence[Sequence[Sequence[float]]],
xs: Sequence[Sequence[float]]) -> Matrix:
"""The 2m x 4 matrix A of the two equations of each view."""
if len(Ps) != len(xs) or len(Ps) < 2:
raise ValueError("linear triangulation needs the same number of cameras and points, at least 2")
A: Matrix = [] # @line L1
for P, x in zip(Ps, xs): # @line L2
u, v = float(x[0]), float(x[1])
A.append([u * P[2][j] - P[0][j] for j in range(4)]) # @line L3
A.append([v * P[2][j] - P[1][j] for j in range(4)]) # @line L3
return A
def triangulate_homogeneous(Ps, xs) -> Vector:
"""The unit 4-vector X that minimizes ||A X||, with X4 >= 0."""
X = nullvec(dlt_rows(Ps, xs)) # @line L4
return [-c for c in X] if X[3] < 0 else X
def linear_triangulation(Ps, xs, eps: float = 1e-12) -> Vector:
"""The 3D point of the homogeneous method. Raises ValueError if the
point is at infinity (|X4| <= eps for the unit vector X)."""
X = triangulate_homogeneous(Ps, xs)
if abs(X[3]) <= eps: # @line L5
raise ValueError("linear triangulation: the point is at infinity")
return [X[0] / X[3], X[1] / X[3], X[2] / X[3]] # @line L6
def linear_triangulation_inhomogeneous(Ps, xs) -> Vector:
"""The 3D point X = (x, y, z) that minimizes ||A (x, y, z, 1)||, by the
normal equations of the 2m x 3 least squares problem. Unlike the
homogeneous method, this one gives the same point after any affine
change of the world frame."""
A = dlt_rows(Ps, xs)
M = [row[:3] for row in A]
b = [[-row[3]] for row in A]
Mt = transpose(M)
return [r[0] for r in solve(mul(Mt, M), mul(Mt, b))]
test_linear_triangulation.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-triangulation/. The authors are listed in prov/8H0B6Z.jsonl.
"""Tests of linear (DLT) triangulation."""
import random
import pytest
from cvgeom import add_noise, random_scene
from cvla import inv, matvec, mul, norm, sub
from linear_triangulation import (dlt_rows, linear_triangulation,
linear_triangulation_inhomogeneous,
triangulate_homogeneous)
P1 = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]
P2 = [[1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]
def rel(a, b):
return norm(sub(a, b)) / max(1.0, norm(b))
def test_worked_example_exact():
X = linear_triangulation([P1, P2], [[0.25, 0.5], [0.0, 0.5]])
assert rel(X, [1.0, 2.0, 4.0]) <= 1e-12
Xh = triangulate_homogeneous([P1, P2], [[0.25, 0.5], [0.0, 0.5]])
assert abs(norm(Xh) - 1.0) <= 1e-12 and Xh[3] > 0
def test_worked_example_noisy():
xs = [[0.25, 0.5], [0.0, 0.52]]
X = linear_triangulation([P1, P2], xs)
assert rel(X, [0.99986, 2.03926, 3.99827]) <= 1e-5
Xi = linear_triangulation_inhomogeneous([P1, P2], xs)
assert rel(Xi, [0.99682, 2.02703, 3.97456]) <= 1e-5
def test_rows_vanish_at_the_true_point():
A = dlt_rows([P1, P2], [[0.25, 0.5], [0.0, 0.5]])
assert len(A) == 4
assert max(abs(v) for v in matvec(A, [1.0, 2.0, 4.0, 1.0])) <= 1e-15
@pytest.mark.parametrize("seed", range(4))
def test_exact_recovery_in_pixels(seed):
rng = random.Random(seed)
sc = random_scene(rng, n=10, n_cams=2 + seed)
for j, X in enumerate(sc["X"]):
xs = [sc["x"][i][j] for i in range(len(sc["P"]))]
assert rel(linear_triangulation(sc["P"], xs), X) <= 1e-8
assert rel(linear_triangulation_inhomogeneous(sc["P"], xs), X) <= 1e-8
def test_noise_error_shrinks_with_views():
rng = random.Random(10)
errs = []
for m in (2, 8):
sc = random_scene(rng, n=30, n_cams=m)
e = 0.0
for j, X in enumerate(sc["X"]):
xs = [add_noise(rng, [sc["x"][i][j]], 0.5)[0] for i in range(m)]
e += norm(sub(linear_triangulation(sc["P"], xs), X))
errs.append(e / 30)
assert errs[1] < errs[0]
assert errs[0] < 0.05
def test_inhomogeneous_is_affine_invariant():
rng = random.Random(11)
sc = random_scene(rng, n=5, n_cams=3)
H = [[2.0, 0.3, 0.0, 10.0], [0.1, 1.0, 0.2, -3.0], [0.0, 0.4, 1.5, 2.0], [0.0, 0.0, 0.0, 1.0]]
Hi = inv(H)
Ps2 = [mul(P, Hi) for P in sc["P"]]
for j in range(5):
xs = add_noise(rng, [sc["x"][i][j] for i in range(3)], 1.0)
X = linear_triangulation_inhomogeneous(sc["P"], xs)
Y = linear_triangulation_inhomogeneous(Ps2, xs)
assert rel(matvec(H, X + [1.0])[:3], Y) <= 1e-8
def test_homogeneous_is_not_translation_invariant():
xs = [[0.25, 0.5], [0.0, 0.52]]
H = [[1.0, 0.0, 0.0, 10.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
Hi = inv(H)
X = linear_triangulation([P1, P2], xs)
Y = linear_triangulation([mul(P1, Hi), mul(P2, Hi)], xs)
back = [Y[0] - 10.0, Y[1], Y[2]]
assert rel(back, X) > 1e-3
def test_homogeneous_is_invariant_under_world_rotation():
rng = random.Random(12)
sc = random_scene(rng, n=3, n_cams=2)
c, s = 0.6, 0.8
H = [[c, -s, 0.0, 0.0], [s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
Ps2 = [mul(P, inv(H)) for P in sc["P"]]
for j in range(3):
xs = add_noise(rng, [sc["x"][i][j] for i in range(2)], 1.0)
X = linear_triangulation(sc["P"], xs)
Y = linear_triangulation(Ps2, xs)
assert rel(matvec(H, X + [1.0])[:3], Y) <= 1e-8
def test_point_at_infinity_raises():
# Two parallel rays along +Z from centers (0, 0, 0) and (1, 0, 0).
with pytest.raises(ValueError):
linear_triangulation([P1, P2], [[0.0, 0.0], [0.0, 0.0]])
def test_needs_two_views():
with pytest.raises(ValueError):
dlt_rows([P1], [[0.0, 0.0]])
History
The linear method applies the direct linear transformation, a standard tool of photogrammetry, to the triangulation of a point. Hartley and Sturm (1997) described the homogeneous and the inhomogeneous linear methods, showed that neither is projective invariant and that the inhomogeneous one is affine invariant, and compared them with the midpoint method and their optimal method. Hartley and Zisserman present the two linear methods in Section 12.2 of their book.
References
- Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 12.2, Linear triangulation methods
- Richard I. Hartley and Peter Sturm, Triangulation, Computer Vision and Image Understanding 68(2), 1997, 146-157, the linear methods, their lack of projective invariance and the comparison with the optimal method
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 11.2.4, Triangulation
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 8H0B6Z Edit this page History Report an error Markdown