Algorithmcore
Eight-point algorithm
Also called Longuet-Higgins eight-point algorithm.
Estimate the essential or fundamental matrix linearly from eight or more matches by SVD, then enforce rank 2 by zeroing the smallest singular value.
- Solves
- Relative pose estimation
- Time
- Θ(n) worst · average · best
- Space
- Θ(n) extra
- Where
- n = the number of point pairs
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- H. C. Longuet Higgins, Richard Hartley, 1981
The eight-point algorithm estimates the fundamental matrix , or the essential matrix of calibrated cameras, from point matches. Each match gives the equation , which is linear in the nine entries of . The algorithm stacks these equations into an matrix , takes the unit vector that makes smallest, and then forces the rank 2 that every fundamental matrix has. Longuet-Higgins (1981) gave it for the essential matrix. This page gives the plain form; on pixel coordinates it must be used with Hartley normalization, which is the normalized eight-point algorithm.
In plain words
Two matching points must satisfy one equation with the unknown matrix, and in that equation each unknown entry appears only to the first power. Each match gives one such equation. The matrix has nine entries, but its overall size does not matter, so eight matches are enough to fix it. With more matches and some noise, no matrix fits all equations, so the algorithm takes the one with the smallest total leftover. A true fundamental matrix always flattens one direction to nothing, but the matrix from the equations usually does not. The last step removes the weakest direction to make it right.
The problem
Input. Point pairs , , , as 2D points that the algorithm extends to . For the essential variant the points are in normalized image coordinates, .
Output. A matrix of rank 2 (or with singular values in the essential variant) with and with its entry of largest absolute value positive. If the pairs are exact images of points in general position seen by two cameras with different centers, the output is the true matrix in this form.
The algorithm
EIGHT-POINT(x1_1 .. x1_n, x2_1 .. x2_n, essential)- 1
for i <- 1 to n - 2
append the row (u2 u1, u2 v1, u2, v2 u1, v2 v1, v2, u1, v1, 1) of the pair (x1_i, x2_i) to A - 3
f <- the right singular vector of A for its smallest singular value - 4
F0 <- the 3 x 3 matrix with rows f[1..3], f[4..6], f[7..9] - 5
(U, diag(s1, s2, s3), V) <- the SVD of F0 - 6
F <- U diag(s1, s2, 0) V^T, or U diag(m, m, 0) V^T with m = (s1 + s2) / 2 if essential - 7
return F / ||F||_F, with the sign that makes its entry of largest absolute value positive
The row of line L2 is the Kronecker product of and , so that its dot product with , the entries of row by row, is . Line L3 minimizes over unit vectors by the singular value decomposition. On exact data has rank 8 and spans its null space. Line L6 replaces by the closest matrix of rank 2 in the Frobenius norm; in the essential variant it gives the closest matrix with two equal singular values and a zero one, as the characterization theorem shows. Line L7 picks one of the matrices so that equal results compare equal.
Example
Take the pose of the running example of epipolar geometry: , , , and . The eight points are , , , , , , and . In normalized coordinates the first two pairs are and .
| line | value |
|---|---|
| L1, L2 | 8 rows; the row of pair 2 is |
| L3 | the singular values of are and 0, so has rank 8 and is the null vector |
| L4 | |
| L5 | the singular values of are |
| L6 | no change: already has rank 2 and two equal singular values |
| L7 |
A check of pair 1: , and its dot product with is 0. Now add to of pair 4. Then has full rank, the singular values of are , line L6 drops the third one, and line L7 gives singular values . The essential variant gives . The algebraic residuals of the eight pairs are now about to instead of 0.
Correctness
The row of line L2 makes . On exact data the true gives , and for eight or more points in general position has rank 8, so line L3 returns the true up to scale. Line L6 then changes nothing, because the true matrix already has rank 2 (and equal singular values in the essential case). On noisy data line L3 minimizes the algebraic error and line L6 is the closest rank 2 matrix, by the theorem of Eckart and Young, or by von Neumann's trace inequality for the essential variant. If all points lie on one plane, has rank at most 6 and the result is not unique. The full proof is below.
Proof: The eight-point algorithm minimizes the algebraic error, forces rank 2 optimally, and recovers F exactly from exact data in general positionfull
We use the notation of the page. The input is pairs of 2D points, written as in image 1 and in image 2. For a matrix we write for its rows put one after the other, so . The canonical form of a nonzero matrix is times the sign of its entry of largest absolute value (on a tie, the first such entry in row order). The singular values of a matrix are .
Claim. (a) The vector of line L3 minimizes over all unit vectors. (b) The matrix of line L6 is a matrix of rank at most 2 that is closest to in the Frobenius norm. In the essential variant, it is a matrix with singular values , , that is closest to . (c) Let be a real matrix of rank 2 with for all , and let have rank 8. Then EIGHT-POINT returns the canonical form of . (d) If there is an invertible with for all (a planar scene, or a camera that only rotates), then has rank at most 6, so the hypothesis of (c) fails.
Lemma 1 (the row). For every matrix , the row of line L2 satisfies .
Proof. Entry of is , and entry of is . So .
So holds exactly when satisfies the epipolar constraint on all pairs.
Lemma 2 (minimum of the algebraic error). Let be an real matrix and let be its smallest singular value, counted as 0 when . Then , and a right singular vector for attains it.
Proof. Let with orthogonal. For a unit vector put , also a unit vector. Then . The last column of gives and equality.
Part (a) is Lemma 2 applied to line L3.
Lemma 3 (closest matrices with given singular value pattern). Let be an SVD. (i) is a matrix of rank at most 2 closest to in the Frobenius norm, at distance . (ii) Among the matrices with singular values for some , with is closest to .
Proof. We use von Neumann's trace inequality: for real matrices and with singular values and , . Let have singular values . Then
For (i), , so the bound is at least , and gives . For (ii), , and the bound is smallest at . The matrix attains the bound, because .
Lines L5 and L6 compute exactly these matrices, so part (b) is Lemma 3.
Proof of part (c). By Lemma 1, for the vector of . The rank of is 8, so its null space is the line spanned by , and . By Lemma 2, line L3 returns a unit vector in this null space, so with . Then has rank 2 and , so line L6 gives back unchanged. Line L7 divides by and fixes the sign by a rule that depends only on the matrix up to a positive factor. So the output is the canonical form of . In the essential variant, if has singular values , then for and line L6 again changes nothing.
Proof of part (d). Let with . For every put . Then , because is orthogonal to . The map is linear and one to one, because is invertible and only for . By Lemma 1 its image, a space of dimension 3, lies in the null space of . So has rank at most . If the camera only rotates, , which is the same case with .
Remark (what the proof does not give). On noisy data the output minimizes the algebraic error under , and then moves to the nearest matrix of rank 2. That two-step result is in general not the matrix of rank 2 with the least algebraic error, and it is not a geometric optimum. The condition of on pixel coordinates, which decides how many digits survive in floating point, is the subject of the normalized eight-point algorithm.
Complexity
Counting arithmetic operations, the loop costs and builds an matrix. The SVD of a matrix with a fixed number of 9 columns costs : a QR decomposition reduces it to a triangle in , and the rest takes a fixed amount of work. Lines L4 to L7 work on matrices and cost . So the time is in all cases, and the extra space is for ; a version that keeps only needs but squares the condition number.
In floating point the accuracy depends on the condition of . With pixel coordinates the nine columns have sizes from about (products of two coordinates) down to 1, and the smallest nonzero singular value is tiny compared with the largest. The normalized version shows a measured case where the ratio drops from about to about 65.
Properties
- Exact on exact data. For exact matches of points in general position, with at least eight pairs and two different camera centers, the output is the true matrix in canonical form.
- Linear and non-iterative. One SVD of an matrix and one of a matrix.
- Algebraic, not geometric. On noisy data line L3 minimizes , which is not a distance in the images. See algebraic and geometric error.
- Two steps, not one. The rank step is done after the least squares step. The result is not the rank 2 matrix with the smallest algebraic error.
- Not covariant. The plain algorithm depends on the origin and the unit of the image coordinates. The normalized form removes this.
- Swap gives the transpose. Exchanging the two images gives the canonical form of .
Variants and improvements
- Normalized eight-point algorithm. Move and scale the points of each image first. This is the standard form; see normalized eight-point algorithm.
- Essential variant. For normalized image coordinates, line L6 sets the singular values to . The pose then comes from essential matrix decomposition.
- Seven points. With seven matches has a two-dimensional null space, and gives a cubic. See seven-point algorithm.
- Five points for calibrated cameras. The five-point algorithm uses the cubic constraints of the essential matrix and needs fewer matches, which matters inside RANSAC: for an inlier ratio of 0.5 and 99% confidence the iteration bound is 1177 samples of eight, against 146 samples of five.
- Geometric refinement. Use the output to start a minimization of the Sampson distance or of the reprojection error with Levenberg-Marquardt.
When to use it
Use the eight-point algorithm when there are eight or more matches with few or no outliers, for example on the inliers that RANSAC found, or as a fast first estimate. Always normalize pixel coordinates first. For calibrated cameras with outliers, the five-point solver inside RANSAC needs fewer samples. When accuracy matters, refine the linear result with a geometric cost.
Pitfalls
- Raw pixel coordinates. Without normalization the result can be wrong by several pixels even for small noise.
- No rank step. Without line L6 the epipolar lines do not meet in one epipole.
- Planar scenes and pure rotation. If all points lie on one plane, or the cameras share their center, has rank at most 6 and many matrices fit. Use a homography for these cases.
- Outliers. One wrong match can move the result far. Use the algorithm inside RANSAC or on its inliers.
- Direction. The output satisfies . The other order of the images needs .
- Sign and scale. and are the same. Compare canonical forms or epipolar distances, not raw entries.
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()
eight_point_algorithm.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eight-point-algorithm/. The authors are listed in prov/ZB0KR6.jsonl.
"""The eight-point algorithm for the fundamental matrix, without normalization.
Given n >= 8 point pairs x1[i] <-> x2[i] (2 entries each), find the 3 x 3
matrix F of rank 2 with x2[i]^T F x1[i] = 0, where the points are made
homogeneous by a third entry 1. Each pair gives one linear equation in the 9
entries of F. The least-squares solution of the stacked equations is the
right singular vector of the smallest singular value; the rank 2 condition
is then forced by the SVD of F.
With essential=True the input is in normalized image coordinates and the
last step forces the singular values (s, s, 0) of an essential matrix.
The result has Frobenius norm 1, and its entry of largest absolute value is
positive. Cost: O(n) to build the n x 9 matrix A and O(n) for its SVD (the
number of columns is fixed at 9), so O(n) in total.
This is the plain method. On pixel coordinates it is badly conditioned; the
page normalized-eight-point-algorithm adds the fix.
"""
from __future__ import annotations
from typing import List, Sequence
from cvla import mul, norm, nullvec, scale, svd, transpose
Matrix = List[List[float]]
def epipolar_row(p1: Sequence[float], p2: Sequence[float]) -> List[float]:
"""The row of A for one pair: the Kronecker product of (u2, v2, 1) and
(u1, v1, 1), so that row . f = x2^T F x1 for F stored row by row."""
y1 = [float(p1[0]), float(p1[1]), 1.0]
y2 = [float(p2[0]), float(p2[1]), 1.0]
return [a * b for a in y2 for b in y1]
def canonical(F: Sequence[Sequence[float]]) -> Matrix:
"""F scaled to Frobenius norm 1, with its entry of largest absolute
value positive (the first such entry, in row order, on a tie)."""
f = norm(F)
if f == 0.0:
raise ValueError("zero matrix")
big = max((x for row in F for x in row), key=abs)
return scale(F, (1.0 if big > 0 else -1.0) / f)
def eight_point(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]],
essential: bool = False) -> Matrix:
"""The plain eight-point algorithm. x1 and x2 are lists of n >= 8 points
(u, v). Returns F (or E if essential=True) in canonical form.
The rank step gives the closest matrix of rank 2 in the Frobenius norm,
or with essential=True the closest matrix with singular values (s, s, 0)."""
n = len(x1)
if n != len(x2):
raise ValueError("x1 and x2 have different lengths")
if n < 8:
raise ValueError("need at least 8 point pairs")
a = []
for i in range(n): # @line L1
a.append(epipolar_row(x1[i], x2[i])) # @line L2
f = nullvec(a) # @line L3
F0 = [f[0:3], f[3:6], f[6:9]] # @line L4
u, s, v = svd(F0) # @line L5
if essential:
m = 0.5 * (s[0] + s[1])
d = [m, m, 0.0]
else:
d = [s[0], s[1], 0.0]
F = mul(mul(u, [[d[0], 0.0, 0.0], [0.0, d[1], 0.0], [0.0, 0.0, d[2]]]), transpose(v)) # @line L6
return canonical(F) # @line L7
def design_singular_values(x1: Sequence[Sequence[float]],
x2: Sequence[Sequence[float]]) -> List[float]:
"""The 9 singular values of A (zero rows added if n < 9), descending.
The number of values near zero is the dimension of the solution space."""
a = [epipolar_row(p, q) for p, q in zip(x1, x2)]
a += [[0.0] * 9 for _ in range(9 - len(a))]
return svd(a)[1]
def algebraic_residuals(F: Sequence[Sequence[float]], x1: Sequence[Sequence[float]],
x2: Sequence[Sequence[float]]) -> List[float]:
"""The values x2[i]^T F x1[i]."""
out = []
for p, q in zip(x1, x2):
y1 = [p[0], p[1], 1.0]
y2 = [q[0], q[1], 1.0]
out.append(sum(y2[r] * F[r][c] * y1[c] for r in range(3) for c in range(3)))
return out
test_eight_point_algorithm.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eight-point-algorithm/. The authors are listed in prov/ZB0KR6.jsonl.
"""Tests of the plain eight-point algorithm."""
import math
import random
import pytest
from cvla import det, inv, matvec, mul, norm, skew, sub, svd, transpose
from eight_point_algorithm import (algebraic_residuals, canonical,
design_singular_values, eight_point,
epipolar_row)
K1 = [[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]
K2 = [[450.0, 0.0, 300.0], [0.0, 460.0, 250.0], [0.0, 0.0, 1.0]]
R_EX = [[0.8, 0.0, 0.6], [0.0, 1.0, 0.0], [-0.6, 0.0, 0.8]]
T_EX = [1.0, 0.0, 0.0]
def rotation(axis, angle):
"""Rodrigues formula, written out (independent of the code under test)."""
a = [c / norm(axis) for c in axis]
k = skew(a)
k2 = mul(k, k)
s, c = math.sin(angle), math.cos(angle)
return [[(1.0 if i == j else 0.0) + s * k[i][j] + (1.0 - c) * k2[i][j]
for j in range(3)] for i in range(3)]
def project(K, X):
y = matvec(K, X)
return [y[0] / y[2], y[1] / y[2]]
def scene(rng, n, R, t, planar=False):
"""n points in front of both cameras, as 3D points of camera 1."""
pts = []
while len(pts) < n:
x, y = rng.uniform(-2.0, 2.0), rng.uniform(-2.0, 2.0)
z = 6.0 + 0.3 * x - 0.2 * y if planar else rng.uniform(4.0, 8.0)
X1 = [x, y, z]
X2 = [a + b for a, b in zip(matvec(R, X1), t)]
if X2[2] > 0.5:
pts.append((X1, X2))
return pts
def true_F(R, t):
E = mul(skew(t), R)
return canonical(mul(mul(transpose(inv(K2)), E), inv(K1)))
def test_row_is_kronecker_product():
row = epipolar_row([2.0, 3.0], [5.0, 7.0])
assert row == [10.0, 15.0, 5.0, 14.0, 21.0, 7.0, 2.0, 3.0, 1.0]
F = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
f = [x for r in F for x in r]
direct = algebraic_residuals(F, [[2.0, 3.0]], [[5.0, 7.0]])[0]
assert abs(sum(a * b for a, b in zip(row, f)) - direct) <= 1e-12
def test_worked_example_essential():
# Normalized coordinates, R about the Y axis, t = (1, 0, 0).
rng = random.Random(1)
pts = scene(rng, 8, R_EX, T_EX)
x1 = [[X1[0] / X1[2], X1[1] / X1[2]] for X1, _ in pts]
x2 = [[X2[0] / X2[2], X2[1] / X2[2]] for _, X2 in pts]
E = eight_point(x1, x2, essential=True)
expected = canonical([[0.0, 0.0, 0.0], [0.6, 0.0, -0.8], [0.0, 1.0, 0.0]])
assert norm(sub(E, expected)) <= 1e-8
s = svd(E)[1]
assert abs(s[0] - s[1]) <= 1e-12 and abs(s[2]) <= 1e-12
def test_one_pair_of_the_example():
# X1 = (0, 0, 5) gives X2 = R X1 + t = (4, 0, 4), so x1 = (0, 0) and x2 = (1, 0).
X2 = [a + b for a, b in zip(matvec(R_EX, [0.0, 0.0, 5.0]), T_EX)]
assert max(abs(a - b) for a, b in zip(X2, [4.0, 0.0, 4.0])) <= 1e-12
E = [[0.0, 0.0, 0.0], [0.6, 0.0, -0.8], [0.0, 1.0, 0.0]]
assert abs(algebraic_residuals(E, [[0.0, 0.0]], [[1.0, 0.0]])[0]) <= 1e-15
@pytest.mark.parametrize("seed", [2, 3, 4])
def test_exact_recovery_in_pixels(seed):
rng = random.Random(seed)
R = rotation([rng.uniform(-1, 1) for _ in range(3)], rng.uniform(0.05, 0.4))
t = [rng.uniform(-1, 1), rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3)]
pts = scene(rng, 20, R, t)
x1 = [project(K1, X1) for X1, _ in pts]
x2 = [project(K2, X2) for _, X2 in pts]
F = eight_point(x1, x2)
Ft = true_F(R, t)
assert norm(sub(F, Ft)) <= 1e-8
assert abs(det(F)) <= 1e-12
assert abs(norm(F) - 1.0) <= 1e-12
for r, p, q in zip(algebraic_residuals(F, x1, x2), x1, x2):
assert abs(r) <= 1e-9 * (1.0 + abs(p[0]) + abs(p[1])) * (1.0 + abs(q[0]) + abs(q[1]))
def test_exactly_eight_points():
rng = random.Random(5)
R = rotation([0.2, 1.0, 0.1], 0.3)
t = [0.9, 0.1, -0.2]
pts = scene(rng, 8, R, t)
x1 = [project(K1, X1) for X1, _ in pts]
x2 = [project(K2, X2) for _, X2 in pts]
assert norm(sub(eight_point(x1, x2), true_F(R, t))) <= 1e-8
def test_noise_gives_rank_two():
rng = random.Random(6)
R = rotation([0.0, 1.0, 0.2], 0.25)
t = [1.0, 0.0, 0.1]
pts = scene(rng, 40, R, t)
x1 = [[c + rng.gauss(0.0, 0.5) for c in project(K1, X1)] for X1, _ in pts]
x2 = [[c + rng.gauss(0.0, 0.5) for c in project(K2, X2)] for _, X2 in pts]
F = eight_point(x1, x2)
s = svd(F)[1]
assert s[2] <= 1e-12 * s[0]
# the epipole of image 1 is the null vector of F, and F e1 = 0 holds
e1 = [row[2] for row in svd(F)[2]]
assert norm(matvec(F, e1)) <= 1e-12
def test_planar_scene_is_degenerate():
rng = random.Random(7)
R = rotation([0.1, 1.0, 0.0], 0.2)
t = [1.0, 0.2, 0.0]
pts = scene(rng, 12, R, t, planar=True)
x1 = [[X1[0] / X1[2], X1[1] / X1[2]] for X1, _ in pts]
x2 = [[X2[0] / X2[2], X2[1] / X2[2]] for _, X2 in pts]
s = design_singular_values(x1, x2)
assert s[5] > 1e-6 * s[0]
assert s[6] <= 1e-10 * s[0] # a three-dimensional solution space
def test_pure_rotation_is_degenerate():
rng = random.Random(8)
R = rotation([0.3, 1.0, 0.1], 0.2)
pts = scene(rng, 12, R, [0.0, 0.0, 0.0])
x1 = [[X1[0] / X1[2], X1[1] / X1[2]] for X1, _ in pts]
x2 = [[X2[0] / X2[2], X2[1] / X2[2]] for _, X2 in pts]
s = design_singular_values(x1, x2)
assert s[5] > 1e-6 * s[0]
assert s[6] <= 1e-10 * s[0]
def test_rejects_bad_input():
with pytest.raises(ValueError):
eight_point([[0.0, 0.0]] * 7, [[0.0, 0.0]] * 7)
with pytest.raises(ValueError):
eight_point([[0.0, 0.0]] * 8, [[0.0, 0.0]] * 9)
def test_canonical_sign_rule():
F = [[0.0, -2.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
c = canonical(F)
assert abs(c[0][1] - 2.0 / math.sqrt(5.0)) <= 1e-15
assert abs(c[1][0] + 1.0 / math.sqrt(5.0)) <= 1e-15
assert canonical(F) == canonical([[-x for x in r] for r in F])
History
Longuet-Higgins (1981) showed that eight point matches in two calibrated views give linear equations for the nine entries of the essential matrix, and that the relative pose follows from it. The method was then used for uncalibrated cameras, where the same equations give the fundamental matrix, with the rank 2 condition added by the SVD. For years it was thought too sensitive to noise for practical use. Hartley (1997) showed that the trouble came from the bad condition of on pixel coordinates and that a simple normalization makes the linear result nearly as good as iterative methods. Hartley and Zisserman (2000, second edition 2004) describe it in Chapter 11.
References
- H. C. Longuet-Higgins, A computer algorithm for reconstructing a scene from two projections, Nature 293, 1981, 133-135, the linear equations in the nine entries of the essential matrix from eight point matches
- Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 11.1, Basic equations, and Section 11.2, The normalized 8-point algorithm (the rank 2 constraint by the SVD)
- Richard I. Hartley, In defense of the eight-point algorithm, IEEE Transactions on Pattern Analysis and Machine Intelligence 19(6), 1997, 580-593, the analysis of the plain algorithm on pixel coordinates and its condition
- Yi Ma, Stefano Soatto, Jana Kosecka and S. Shankar Sastry, An Invitation to 3-D Vision, Springer, 2004, Chapter 5, Section 5.2.1 (the eight-point linear algorithm and the projection onto the essential space)
Where this leads
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 ZB0KR6 Edit this page History Report an error Markdown