Algorithmadvanced
Hartley-Sturm optimal triangulation
Also called polynomial triangulation, optimal two-view triangulation.
Find the two-view triangulation of least reprojection error exactly, by reducing it to the roots of a degree 6 polynomial over the pencil of epipolar lines.
- Solves
- Point triangulation
- Time
- Θ(1) worst · average · best
- Space
- Θ(1) extra
- Where
- d = the degree of the polynomial, always 6
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Richard Hartley, Peter Sturm, 1997
Optimal triangulation finds the 3D point whose two projections are closest to the measured image points, in the sense of the sum of the squared image distances: the reprojection error. Under independent Gaussian noise on the image points this is the maximum likelihood estimate. The method of Hartley and Sturm does not search over 3D points. It looks for the corrected image points , that satisfy the epipolar constraint of the fundamental matrix and are closest to the measured points. Each such pair lies on a pair of matching epipolar lines, and these lines form a family with one parameter . After a Euclidean change of each image frame, the cost is a simple rational function of , and its stationary points are the real roots of a polynomial of degree 6. The best root gives the corrected points, which back-project to rays that meet, so any linear triangulation gives the point exactly. The result depends only on and the image points, so the method is projective invariant.
In plain words
Each photo shows the point a little off from where it should be, so the two lines of sight do not quite meet. The method asks: what is the smallest shift of the two dots that makes the lines meet? It does not try 3D points. Instead it looks at the pairs of lines in the two photos on which matching dots must lie. These pairs can be described with one number. For each value of that number, the needed shift is easy to write down. The best value is found by solving one equation, and the shifted dots give the point directly.
The problem
Input. A fundamental matrix of rank 2, or two camera matrices , from which is formed, and two measured points , in Euclidean image coordinates (pixels with square pixels and no skew, or normalized coordinates).
Output. The pair with that minimizes , and the 3D point that projects to them.
The algorithm
Lines L1 to L3 move and to the origin of their images and turn each image about the origin so that the epipoles lie on the axis, at and . Then has the form
The epipolar line in image 1 through is , and the matching line in image 2 is . The cost of the best pair on these two lines is the sum of the squared distances from the origin to them:
OPTIMAL-TRIANGULATION(F, x_1, x_2)- 1
T_1, T_2 <- translations that move x_1, x_2 to the origin; F <- T_2^-T F T_1^-1 - 2
e_1, e_2 <- right and left null vectors of F, scaled so that e_x^2 + e_y^2 = 1 - 3
R_1, R_2 <- rotations with R_1 e_1 = (1, 0, f), R_2 e_2 = (1, 0, f'); F <- R_2 F R_1^T - 4
f, f' <- third entries of e_1, e_2; a, b, c, d <- F_22, F_23, F_32, F_33 - 5
g(t) <- t ((a t + b)^2 + f'^2 (c t + d)^2)^2 - (a d - b c)(1 + f^2 t^2)^2 (a t + b)(c t + d) - 6
t_min <- the real root of g, or t = infinity, with the least s(t) - 7
l_1 <- (t f, 1, -t); l_2 <- (-f'(c t + d), a t + b, c t + d), at t = t_min - 8
x^_1, x^_2 <- the points of l_1, l_2 closest to the origin - 9
x^_i <- T_i^-1 R_i^T x^_i - 10
X <- the linear triangulation of x^_1, x^_2
The point of the line closest to the origin is . At the lines are and , and .
Example
Take and , in normalized coordinates. The point has the images and . Move the second one by to .
| line | value |
|---|---|
| L2 to L4 | , , , , , |
| L5 | |
| L6 | real roots and , with and ; ; so |
| L9 | , |
| L10 | , reprojection error |
On the same data, linear triangulation gives with the larger reprojection error . In the simpler case , with the images and , the epipolar lines are horizontal, the polynomial has degree 1, and the method moves both points to the height . The result is , with reprojection error .
Correctness
Translations and rotations of the images keep distances and transform in a matching way, so the normal form above loses nothing. Every corrected point other than the epipole lies on one line of the pencil, and its epipolar line in image 2 is . So the least cost for a given is the sum of the squared distances from the origin to the two lines, , and pairs that contain an epipole are never better. On the projective line of the function reaches its minimum, either at or where . Clearing denominators in gives exactly . So line L6 finds the optimal , and the feet of the perpendiculars are the optimal pair. The corrected points satisfy the epipolar constraint, so their rays meet, and the point where they meet has a reprojection error equal to the optimal cost. The full proof is in the proof file of this page.
Proof: The real roots of the degree 6 polynomial and the point at infinity of the pencil contain the minimizer of the two-view reprojection errorfull
We use the notation of the page. is a fundamental matrix of rank 2 with for matching points. The measured points , are not at the epipoles. Image coordinates are Euclidean, so is the Euclidean distance in each image. The arithmetic is exact (real RAM). The cost of a pair is .
Claim. (a) The pair returned by lines L1 to L9 satisfies and has the least cost among all pairs that satisfy it. (b) If comes from finite cameras , with distinct centers and the rays of the corrected points meet at a finite point , then line L10 returns , and has the least reprojection error among all points off the baseline.
Lemma 1 (Euclidean changes of frame). Let , be Euclidean motions of the two images (here ). Replacing each point of image by and by keeps the epipolar constraint and all distances. So it is enough to prove part (a) in the new frames.
Proof. , and Euclidean motions keep distances. Line L9 applies the inverse motions.
Lemma 2 (the normal form of ). After lines L1 to L3, , the epipoles are and , and
Proof. Line L1 moves the points to the origin. Line L2 scales the epipole so that ; this is possible because the point at the origin is not the epipole, so . The rotation of line L3 maps it to and fixes the origin. Now says that the first column of is times the third, and says that the first row is times the third. Naming the lower right block gives the form above. The first row and the first column are combinations of the others, so the rank of equals the rank of this block, which must be 2.
Lemma 3 (the pencil). For , let , the line through and , and . For , let , the line through in the direction , and . Then every point lies on exactly one , and its epipolar line is up to a nonzero factor.
Proof. The lines through meet the line in one point , or are parallel to it (); the two vectors span the line, and the cross product gives . A point on this line is with , so . This is not zero, because the null space of is spanned by , whose first entry is 1. The case is the same with .
Lemma 4 (the cost along the pencil). The distance from the origin to the line is , reached at the point . So
with the value where the second denominator is 0, and .
Proof. The foot of the perpendicular from the origin to is , which is the stated homogeneous point, at the stated distance. Insert the lines of Lemma 3. The second denominator is 0 only if and , and then is the line at infinity (it is not , since and do not vanish together when ).
Lemma 5 (reduction to the pencil). The least cost over pairs that satisfy the epipolar constraint equals over , and the feet of the perpendiculars at a minimizing give an optimal pair.
Proof. Take a pair that satisfies the constraint with . By Lemma 3, lies on and on for one , so its cost is at least . Conversely, the two feet at any satisfy the constraint: the foot on is , for which , or a point whose epipolar line is , which contains the second foot. Their cost is .
It remains to treat the pairs with , which have cost at least (infinite if ). If , then gives . If , then and . So such pairs are never better than the pencil. The pairs with cost at least , and , with if . So they are never better either.
Lemma 6 (the stationary points). Where the second denominator is positive,
so if and only if .
Proof. The derivative of is . For the second term,
and . Multiplying by the positive number gives .
Proof of part (a). On the projective line , which is compact, is continuous as a map to , so it reaches its minimum, and the minimum is finite by Lemma 5 (for example or is finite). A minimizer is either or a finite point with where , that is, a real root of by Lemma 6. If is the zero polynomial, then is constant where , and is also a minimizer. Line L6 evaluates at all real roots of and at and keeps the least, so it finds a minimizer. Lines L7 and L8 build the feet of Lemma 4, which form an optimal pair by Lemma 5, and line L9 maps them back by Lemma 1.
Proof of part (b). The corrected points satisfy the epipolar constraint, so their back-projected rays lie in one epipolar plane. By assumption they meet at the finite point , so , and the linear method of line L10 returns (see linear triangulation). The reprojection error of equals the cost of the corrected pair. Any point off the baseline projects to a pair that satisfies the epipolar constraint, so by part (a) its reprojection error is at least that cost.
Remark (projective invariance). The output of lines L1 to L9 depends only on and the measured points. If the cameras are replaced by for an invertible matrix , the fundamental matrix stays the same up to scale, so the corrected points do not change, and the triangulated point becomes .
Remark (floating point). The roots of are found numerically, so line L6 compares a few values of that carry rounding errors; near a double root the chosen can be off by about the square root of the machine precision, which changes only to second order.
Complexity
All steps work on objects of fixed size: matrices, a polynomial of degree 6 and at most 7 candidate values of . So the method takes time and space per point. In practice it is several times slower than linear triangulation, mostly because of the root finding.
Properties
- Optimal. It gives the global minimum of the two-view reprojection error, not a local one; it is the maximum likelihood estimate under independent isotropic Gaussian image noise.
- Projective invariant. It uses only and the image points. A projective change of the world frame gives the same corrected points and the transformed 3D point.
- Exact on exact data. If the measured points already satisfy the epipolar constraint, the cost is 0, they are not moved, and the point is exact.
- Two views only. The pencil argument needs one pair of epipolar lines. For three or more views the problem has many more stationary points, and other methods are used.
- Euclidean images. The cost is a distance in each image, so the image coordinates must have square pixels and no skew, or be normalized.
Variants and improvements
- Iterative correction. Lindstrom (2010) finds the same optimal pair with a short iteration that needs no polynomial roots; in practice two steps are enough, and the result is much faster to compute.
- First-order correction. One step of correction along the gradient of the epipolar constraint gives the pair that minimizes the Sampson distance, a first-order approximation of the optimal cost.
- Triangulation in more views. For three or more views, local minimization of the reprojection error from a linear start, or a full bundle adjustment, is the usual approach.
- Calibrated cameras. With an essential matrix, for example from the five-point algorithm, the same method works on normalized image points, and the cost is then measured in normalized units instead of pixels.
When to use it
Use it when two views must give the best possible point under image noise, for example to evaluate other methods, to triangulate in a projective reconstruction where Euclidean methods do not apply, or to initialize a reconstruction with as little bias as possible. When speed matters and many points must be triangulated, linear triangulation followed by a few Gauss-Newton steps, or the iterative correction of Lindstrom, gives almost the same result.
Pitfalls
- Non-Euclidean image frames. Running the method on pixel coordinates with skew, or on coordinates after a projective normalization, minimizes the wrong distance.
- Points near the epipole. The rotation of line L3 is not defined when a measured point is at the epipole, and it is badly conditioned near it.
- Root finding. Two real roots can be close or form a double root; take the real parts of nearly real complex roots as candidates, and do not forget the candidate .
- Back-transformation. The corrected points must be mapped back with the inverses of both the rotation and the translation, in that order.
- Points behind a camera. The method minimizes an image distance and can return a point behind a camera. Check cheirality if the cameras are known in a Euclidean 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()
optimal_triangulation.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-triangulation/. The authors are listed in prov/FJGF9W.jsonl.
"""Hartley-Sturm optimal two-view triangulation.
Given a fundamental matrix F (x2^T F x1 = 0) and two measured image points
x1, x2, find the points x1h, x2h with x2h^T F x1h = 0 that minimize
d(x1, x1h)^2 + d(x2, x2h)^2. The epipolar lines through x1h and x2h form a
pencil with one parameter t; after a Euclidean change of each image frame
the cost is a rational function s(t), and its stationary points are the
real roots of a polynomial g(t) of degree 6 (Hartley and Sturm 1997,
Hartley and Zisserman 2004, Algorithm 12.1). The corrected points are
then triangulated exactly by the linear method.
The image coordinates must be in a Euclidean frame (pixels with square
pixels and no skew, or normalized coordinates), because the cost is a
Euclidean distance in the image.
Cost: Theta(1).
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
from cvla import inv, matvec, mul, nullvec, polyroots_real, skew, transpose
Matrix = List[List[float]]
Vector = List[float]
# ------------------------------------------------------------ polynomials
def _pmul(p: Sequence[float], q: Sequence[float]) -> Vector:
"""Product of two polynomials, coefficients highest power first."""
out = [0.0] * (len(p) + len(q) - 1)
for i, a in enumerate(p):
for j, b in enumerate(q):
out[i + j] += a * b
return out
def _padd(p: Sequence[float], q: Sequence[float]) -> Vector:
n = max(len(p), len(q))
p = [0.0] * (n - len(p)) + list(p)
q = [0.0] * (n - len(q)) + list(q)
return [a + b for a, b in zip(p, q)]
def _pscale(p: Sequence[float], k: float) -> Vector:
return [k * a for a in p]
def cost_polynomial(a: float, b: float, c: float, d: float, f: float, f2: float) -> Vector:
"""The coefficients (degree 6 first) of
g(t) = t ((a t + b)^2 + f2^2 (c t + d)^2)^2
- (a d - b c) (1 + f^2 t^2)^2 (a t + b) (c t + d)."""
atb, ctd = [a, b], [c, d]
q = _padd(_pmul(atb, atb), _pscale(_pmul(ctd, ctd), f2 * f2))
left = _pmul([1.0, 0.0], _pmul(q, q))
r = [f * f, 0.0, 1.0]
right = _pscale(_pmul(_pmul(r, r), _pmul(atb, ctd)), a * d - b * c)
return _padd(left, _pscale(right, -1.0))
def cost_s(t: float, a: float, b: float, c: float, d: float, f: float, f2: float) -> float:
"""s(t) = t^2 / (1 + f^2 t^2) + (c t + d)^2 / ((a t + b)^2 + f2^2 (c t + d)^2).
t = math.inf gives the limit 1/f^2 + c^2 / (a^2 + f2^2 c^2)."""
if math.isinf(t):
first = math.inf if f == 0 else 1.0 / (f * f)
den = a * a + f2 * f2 * c * c
return first + (c * c / den if den > 0 else math.inf)
den = (a * t + b) ** 2 + f2 * f2 * (c * t + d) ** 2
second = (c * t + d) ** 2 / den if den > 0 else math.inf
return t * t / (1.0 + f * f * t * t) + second
# ------------------------------------------------------------ geometry
def fundamental_from_cameras(P1: Sequence[Sequence[float]],
P2: Sequence[Sequence[float]]) -> Matrix:
"""F = [e2]_x P2 P1^+, with e2 = P2 C1 and P1^+ = P1^T (P1 P1^T)^-1."""
C1 = nullvec(P1)
e2 = matvec(P2, C1)
P1t = transpose(P1)
pinv = mul(P1t, inv(mul(P1, P1t)))
return mul(skew(e2), mul(P2, pinv))
def _translation(x: Sequence[float]) -> Matrix:
return [[1.0, 0.0, -x[0]], [0.0, 1.0, -x[1]], [0.0, 0.0, 1.0]]
def _unit_epipole(e: Sequence[float]) -> Vector:
n = math.hypot(e[0], e[1])
if n <= 1e-12 * max(1.0, abs(e[2])):
raise ValueError("optimal triangulation: an image point is at the epipole")
return [e[0] / n, e[1] / n, e[2] / n]
def _closest_to_origin(line: Sequence[float]) -> Vector:
lam, mu, nu = line
return [-lam * nu, -mu * nu, lam * lam + mu * mu]
def optimal_correction(F: Sequence[Sequence[float]], x1: Sequence[float],
x2: Sequence[float], details: bool = False):
"""The corrected points (x1h, x2h) with x2h^T F x1h = 0 of least
d(x1, x1h)^2 + d(x2, x2h)^2, and that least cost."""
T1, T2 = _translation(x1), _translation(x2) # @line L1
T1i, T2i = inv(T1), inv(T2) # @line L1
Fn = mul(transpose(T2i), mul(F, T1i)) # @line L1
e1 = _unit_epipole(nullvec(Fn)) # @line L2
e2 = _unit_epipole(nullvec(transpose(Fn))) # @line L2
R1 = [[e1[0], e1[1], 0.0], [-e1[1], e1[0], 0.0], [0.0, 0.0, 1.0]] # @line L3
R2 = [[e2[0], e2[1], 0.0], [-e2[1], e2[0], 0.0], [0.0, 0.0, 1.0]] # @line L3
Fr = mul(R2, mul(Fn, transpose(R1))) # @line L3
f, f2 = e1[2], e2[2] # @line L4
a, b, c, d = Fr[1][1], Fr[1][2], Fr[2][1], Fr[2][2] # @line L4
g = cost_polynomial(a, b, c, d, f, f2) # @line L5
cands = polyroots_real(g) + [math.inf] # @line L6
t = min(cands, key=lambda u: cost_s(u, a, b, c, d, f, f2)) # @line L6
if math.isinf(t): # @line L7
l1, l2 = [f, 0.0, -1.0], [-f2 * c, a, c] # @line L7
else: # @line L7
l1 = [t * f, 1.0, -t] # @line L7
l2 = [-f2 * (c * t + d), a * t + b, c * t + d] # @line L7
p1, p2 = _closest_to_origin(l1), _closest_to_origin(l2) # @line L8
q1 = matvec(T1i, matvec(transpose(R1), p1)) # @line L9
q2 = matvec(T2i, matvec(transpose(R2), p2)) # @line L9
x1h = [q1[0] / q1[2], q1[1] / q1[2]] # @line L9
x2h = [q2[0] / q2[2], q2[1] / q2[2]] # @line L9
cost = ((x1h[0] - x1[0]) ** 2 + (x1h[1] - x1[1]) ** 2
+ (x2h[0] - x2[0]) ** 2 + (x2h[1] - x2[1]) ** 2)
if details:
return x1h, x2h, cost, {"F": Fr, "f": f, "f2": f2, "abcd": (a, b, c, d),
"g": g, "roots": cands[:-1], "t": t,
"s": cost_s(t, a, b, c, d, f, f2)}
return x1h, x2h, cost
def triangulate_dlt(P1, P2, x1, x2) -> Vector:
"""The linear (DLT) triangulation of two image points."""
A = []
for P, (u, v) in ((P1, x1), (P2, x2)):
A.append([u * P[2][k] - P[0][k] for k in range(4)])
A.append([v * P[2][k] - P[1][k] for k in range(4)])
X = nullvec(A)
if X[3] == 0.0:
raise ValueError("optimal triangulation: the point is at infinity")
return [X[0] / X[3], X[1] / X[3], X[2] / X[3]]
def optimal_triangulation(P1, P2, x1, x2) -> Tuple[Vector, Vector, Vector, float]:
"""The 3D point of least reprojection error for the cameras P1, P2 and
the image points x1, x2. Returns (X, x1h, x2h, cost)."""
F = fundamental_from_cameras(P1, P2)
x1h, x2h, cost = optimal_correction(F, x1, x2)
X = triangulate_dlt(P1, P2, x1h, x2h) # @line L10
return X, x1h, x2h, cost
def reprojection_cost(P1, P2, X, x1, x2) -> float:
"""The sum of the squared image distances of the projections of X."""
s = 0.0
for P, x in ((P1, x1), (P2, x2)):
q = matvec(P, list(X) + [1.0])
s += (q[0] / q[2] - x[0]) ** 2 + (q[1] / q[2] - x[1]) ** 2
return s
test_optimal_triangulation.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-triangulation/. The authors are listed in prov/FJGF9W.jsonl.
"""Tests of Hartley-Sturm optimal triangulation."""
import math
import random
import pytest
from cvgeom import add_noise, camera_matrix, random_scene, rot_y
from cvla import inv, matvec, mul, norm, sub, transpose
from optimal_triangulation import (cost_s, fundamental_from_cameras,
optimal_correction, optimal_triangulation,
reprojection_cost, triangulate_dlt)
I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
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]]
P2B = camera_matrix(I3, rot_y(-0.3), [-1.0, 0.0, 0.2])
Y1 = [0.25, 0.5]
Y2N = [-0.2741747441668867, 0.48329905176727356]
def rel(a, b):
return norm(sub(a, b)) / max(1.0, norm(b))
def epipolar(F, x1, x2):
return sum((x2 + [1.0])[i] * F[i][j] * (x1 + [1.0])[j] for i in range(3) for j in range(3))
def noisy_cases(seed, count, sigma=2.0):
rng = random.Random(seed)
out = []
for _ in range(count):
sc = random_scene(rng, n=1, n_cams=2, max_angle=0.5)
xa, xb = add_noise(rng, [sc["x"][0][0], sc["x"][1][0]], sigma)
out.append((sc["P"][0], sc["P"][1], xa, xb, sc["X"][0]))
return out
def test_worked_example_pure_translation():
X, x1h, x2h, cost = optimal_triangulation(P1, P2, [0.25, 0.5], [0.0, 0.52])
assert rel(x1h, [0.25, 0.51]) <= 1e-12 and rel(x2h, [0.0, 0.51]) <= 1e-12
assert rel(X, [1.0, 2.04, 4.0]) <= 1e-12
assert abs(cost - 2e-4) <= 1e-15
def test_worked_example_general():
F = fundamental_from_cameras(P1, P2B)
x1h, x2h, cost, info = optimal_correction(F, Y1, Y2N, details=True)
assert abs(abs(info["f"]) - 0.464944) <= 1e-6
assert abs(abs(info["f2"]) - 0.210505) <= 1e-6
assert len(info["roots"]) == 2
assert abs(info["roots"][0] - 0.0094559) <= 1e-6
assert abs(info["roots"][1] - 11.419014) <= 1e-5
assert abs(cost - 1.880302e-4) <= 1e-9
assert rel(x1h, [0.247761, 0.509187]) <= 1e-6
assert rel(x2h, [-0.273185, 0.473418]) <= 1e-6
X = triangulate_dlt(P1, P2B, x1h, x2h)
assert rel(X, [1.054300, 2.166745, 4.255303]) <= 1e-6
Xl = triangulate_dlt(P1, P2B, Y1, Y2N)
assert reprojection_cost(P1, P2B, Xl, Y1, Y2N) > cost
a, b, c, d = info["abcd"]
for t in info["roots"]:
h = 1e-6 * max(1.0, abs(t))
ds = (cost_s(t + h, a, b, c, d, info["f"], info["f2"])
- cost_s(t - h, a, b, c, d, info["f"], info["f2"])) / (2 * h)
assert abs(ds) <= 1e-6
def test_exact_data():
rng = random.Random(1)
for _ in range(6):
sc = random_scene(rng, n=1, n_cams=2, max_angle=0.5)
xa, xb = sc["x"][0][0], sc["x"][1][0]
X, x1h, x2h, cost = optimal_triangulation(sc["P"][0], sc["P"][1], xa, xb)
assert rel(X, sc["X"][0]) <= 1e-8
assert norm(sub(x1h, xa)) <= 1e-8 * norm(xa)
assert cost <= 1e-12 * norm(xa) ** 2
def test_corrected_points_satisfy_the_epipolar_constraint():
for Pa, Pb, xa, xb, _ in noisy_cases(2, 6):
F = fundamental_from_cameras(Pa, Pb)
x1h, x2h, _ = optimal_correction(F, xa, xb)
scale = norm(F) * (norm(x1h) + 1.0) * (norm(x2h) + 1.0)
assert abs(epipolar(F, x1h, x2h)) <= 1e-12 * scale
def test_cost_is_reprojection_error_and_beats_linear():
for Pa, Pb, xa, xb, Xt in noisy_cases(3, 6):
X, _, _, cost = optimal_triangulation(Pa, Pb, xa, xb)
assert abs(reprojection_cost(Pa, Pb, X, xa, xb) - cost) <= 1e-8 * max(1.0, cost)
Xl = triangulate_dlt(Pa, Pb, xa, xb)
assert cost <= reprojection_cost(Pa, Pb, Xl, xa, xb) + 1e-9
assert cost <= reprojection_cost(Pa, Pb, Xt, xa, xb) + 1e-9
def test_global_minimum_over_the_pencil():
for Pa, Pb, xa, xb, _ in noisy_cases(4, 4, sigma=5.0):
F = fundamental_from_cameras(Pa, Pb)
_, _, _, info = optimal_correction(F, xa, xb, details=True)
a, b, c, d = info["abcd"]
best = min(cost_s(math.tan(math.pi * (k + 0.5) / 4000 - math.pi / 2),
a, b, c, d, info["f"], info["f2"]) for k in range(4000))
assert info["s"] <= best + 1e-12
def test_local_perturbations_do_not_help():
rng = random.Random(5)
for Pa, Pb, xa, xb, _ in noisy_cases(5, 3):
X, _, _, cost = optimal_triangulation(Pa, Pb, xa, xb)
for _ in range(30):
Z = [x + rng.gauss(0, 1e-3) for x in X]
assert reprojection_cost(Pa, Pb, Z, xa, xb) >= cost - 1e-9
def test_projective_invariance():
rng = random.Random(6)
H = [[rng.uniform(-1, 1) + (2.0 if i == j else 0.0) for j in range(4)] for i in range(4)]
Hi = inv(H)
for Pa, Pb, xa, xb, _ in noisy_cases(7, 3):
X, x1h, x2h, cost = optimal_triangulation(Pa, Pb, xa, xb)
X2, y1h, y2h, cost2 = optimal_triangulation(mul(Pa, Hi), mul(Pb, Hi), xa, xb)
assert rel(y1h, x1h) <= 1e-8 and rel(y2h, x2h) <= 1e-8
assert abs(cost2 - cost) <= 1e-8 * max(1.0, cost)
Xh = matvec(H, X + [1.0])
assert rel([v / Xh[3] for v in Xh[:3]], X2) <= 1e-7
def test_point_at_the_epipole_raises():
C2 = [-v for v in matvec(transpose(rot_y(-0.3)), [-1.0, 0.0, 0.2])]
e1 = [C2[0] / C2[2], C2[1] / C2[2]]
F = fundamental_from_cameras(P1, P2B)
with pytest.raises(ValueError):
optimal_correction(F, e1, Y2N)
History
Hartley and Sturm (1997) studied the triangulation of a point from two views with known cameras. They showed that the linear and midpoint methods are not projective invariant, reduced the minimization of the reprojection error to the real roots of a polynomial of degree 6, and showed in experiments that the optimal method is more accurate than the others. Hartley and Zisserman present the method as Algorithm 12.1 of their book. Lindstrom (2010) gave a fast iterative method that reaches the same optimum in a few steps.
References
- Richard I. Hartley and Peter Sturm, Triangulation, Computer Vision and Image Understanding 68(2), 1997, 146-157, the polynomial method, its projective invariance and the comparison with linear and midpoint methods
- Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Sections 12.3 to 12.5, Algorithm 12.1
- Peter Lindstrom, Triangulation Made Easy, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2010, 1554-1561, the fast iterative alternative to the polynomial 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 FJGF9W Edit this page History Report an error Markdown