Algorithmcore
Normalized eight-point algorithm
Also called Hartley's eight-point algorithm.
The eight-point algorithm run on Hartley-normalized points and mapped back by F = T2^T G T1. The normalization makes the linear system well conditioned and the result stable.
- 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
- Richard Hartley, 1997
The normalized eight-point algorithm estimates the fundamental matrix from point matches in pixels. It first gives each image its own similarity or that moves the centroid of its points to the origin and makes their mean distance to it , which is Hartley normalization. Then it runs the eight-point algorithm on the moved points, forces rank 2 there, and maps the result back by . Hartley (1997) showed that this cheap change turns a method thought to be useless on real images into a good one. It is the standard linear estimate of and the usual start of a geometric refinement.
In plain words
Pixel coordinates are numbers of a few hundred, and the equations of the eight-point algorithm multiply them together, so the table of equations mixes numbers near 1 with numbers near a hundred thousand. In such a table small errors in the big numbers hide the information in the small ones. The fix is to change units in each image before solving. Move the points so that they sit around the origin, and shrink them so that a typical point is about one unit away. Solve in these units, make the answer have the right form, and then convert it back to pixels. The extra work is tiny, and the answer becomes much more accurate.
The problem
Input. Point pairs , , , as 2D pixel points that the algorithm extends to . The points of each image must not all be equal.
Output. A matrix of rank 2 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 fundamental matrix in this form.
The algorithm
NORMALIZED-EIGHT-POINT(x1_1 .. x1_n, x2_1 .. x2_n)- 1
T1 <- the similarity that moves the centroid of the x1_i to 0 and makes their mean distance to it sqrt(2) - 2
T2 <- the same similarity for the x2_i - 3
for i <- 1 to n - 4
y1 <- T1 x1_i ; y2 <- T2 x2_i - 5
append the row (y2[1] y1^T, y2[2] y1^T, y2[3] y1^T) to A - 6
g <- the right singular vector of A for its smallest singular value - 7
G <- the 3 x 3 matrix with rows g[1..3], g[4..6], g[7..9] - 8
(U, diag(s1, s2, s3), V) <- the SVD of G - 9
G <- U diag(s1, s2, 0) V^T - 10
F <- T2^T G T1 - 11
return F / ||F||_F, with the sign that makes its entry of largest absolute value positive
Lines L1 and L2 compute each similarity from its own points: , with the centroid and for the mean distance to it. Lines L3 to L9 are the eight-point algorithm on the moved points: line L5 is the row with , line L6 minimizes over unit vectors by the SVD, and line L9 forces rank 2. The rank step is done before line L10, so it acts on the well scaled matrix. Line L10 undoes the change: if with and , then . Since and are invertible, has rank 2 as has.
Example
Take the eight points of the eight-point example seen by two cameras with . The pixel points of image 1 are , , , , , , and ; those of image 2 are , , , , , , and .
| line | value |
|---|---|
| L1 | scale , translation |
| L2 | scale , translation |
| L3 to L5 | 8 rows with entries of size about 1 |
| L6 | the singular values of are and 0; the ratio of the largest to the smallest nonzero one is 65.0 |
| L7 to L9 | has rank 2 already, so line L9 changes it only by rounding |
| L10, L11 |
The output is the canonical form of . The epipolar distances of the eight points are about pixels. Without lines L1 and L2, the nonzero singular values of run from down to , a ratio of . On these exact data both forms still give the true , but the difference shows with noise. In a test with 30 points, 10 random scenes and Gaussian noise of 1 pixel, the mean distance of the points to their epipolar lines was about 0.67 pixels for the normalized form and about 3.5 pixels for the plain form, and the normalized form was better in 8 of the 10 scenes.
Correctness
Line L10 is a change of coordinates: . On exact data, the moved pairs are exact matches for the fundamental matrix , so the eight-point algorithm on them returns this matrix up to scale, and line L10 gives back . The result has rank 2 because and are invertible. If the points of image 1 are moved by a similarity and those of image 2 by , the normalized points change only by a rotation and a reflection, and the output becomes the canonical form of . The full proof is below.
Proof: The normalized eight-point algorithm recovers F exactly from exact data, and its output moves with the data under similaritiesfull
We use the notation of the page. The input is pairs of 2D points, written as and . For a matrix we write for its rows put one after the other. The canonical form of a nonzero matrix is the matrix divided by its Frobenius norm, times the sign of its entry of largest absolute value. is the matrix of the plain eight-point algorithm on the input points, and is the matrix of line L5, built from the moved points and .
Claim. (a) Let be a real matrix of rank 2 with for all , and let have rank 8. Then the algorithm returns the canonical form of . (b) On any input, the output has rank at most 2, and line L9 gives the matrix of rank at most 2 closest to in the Frobenius norm, in the normalized coordinates. (c) Let and be similarities of the two images, and move the input to and . If the smallest singular value of is simple and the third singular value of is simple, the output for the moved input is the canonical form of , where is the output for the original input.
Lemma 1 (change of coordinates). Let and be invertible. A matrix satisfies for all if and only if satisfies for all . The map is linear, one to one, and keeps the rank.
Proof. . The inverse map is , and multiplication by invertible matrices does not change the rank.
By Lemma 1 of the eight-point proof, exactly when satisfies the constraints, and exactly when does. So Lemma 1 here says that the linear map sends the null space of onto the null space of , and the two null spaces have the same dimension. Both matrices have 9 columns, so has rank 8 exactly when has rank 8.
The similarities of lines L1 and L2 are invertible. Their last row is , and their scale is finite and positive, because the code stops when all points of one image coincide ().
Proof of part (a). Put . By Lemma 1, has rank 2 and satisfies the constraints on the moved points, so . Since has rank 8, the null space of is the line spanned by . Line L6 returns a unit vector in it (Lemma 2 of the eight-point proof), so line L7 gives with . This matrix has rank 2, so its third singular value is 0, and line L9 does not change it. Line L10 gives , and line L11 gives the canonical form of , for every .
Proof of part (b). Line L9 is Lemma 3 (i) of the eight-point proof, applied to . The output has the rank of by Lemma 1, so at most 2.
Part (b) does not say that the output is the matrix of rank 2 closest to anything in the original coordinates. The rank step happens in the normalized frame, as Hartley (1997) does it.
Lemma 2 (the similarity part of the normalization). Let be a similarity of the plane, for , with , a orthogonal matrix and . Let be the normalizing similarity of the points and that of the points . Then with .
Proof. The centroid of the moved points is , where is the old centroid, and each distance to it is multiplied by . So subtracts and scales by . Then .
Proof of part (c). By Lemma 2, the moved points in the normalized frame are and , with and orthogonal. For a matrix put . Then and . So the new matrix satisfies for all , and the unit minimizer of line L6 moves from to when the minimizer is unique up to sign. The SVD of is that of with and multiplied by and , so line L9 also commutes with when the third singular value is simple. Line L10 for the moved input gives
using from Lemma 2. Up to the sign of , this is before line L11, and line L11 removes the sign.
Remark (the plain algorithm is not covariant). Without lines L1 and L2, a translation of the pixel frame changes by a change of variables in that is not orthogonal, so the minimizer of over unit vectors does not move with the data. The page shows a measured example of the effect on the accuracy. That the normalization improves the accuracy is a property of the condition number of (Hartley 1997); it is supported by analysis and by experiments, not by a theorem on the error of the output.
Complexity
Lines L1 and L2 cost , the loop costs , and the SVD of the matrix costs because the number of columns is fixed. Lines L7 to L11 work on matrices and cost . So the time is and the extra space is for , the same as the plain algorithm.
In floating point the gain is in the condition number of . After normalization each entry of a row is a product of two numbers of size about 1, so all nine columns of have about the same size. Hartley (1997) analyses the condition number of and shows how it grows with the size of the pixel coordinates when no normalization is done.
Properties
- Exact on exact data. Like the plain algorithm, for eight or more exact matches in general position with two different camera centers.
- Covariant under similarities. Moving the points of each image by a similarity changes the output in the same way as the true . The plain algorithm does not have this property.
- Linear and non-iterative. The cost is about the same as the plain algorithm.
- Algebraic, not geometric. The output minimizes the algebraic error of the normalized points. It is close to, but not equal to, the maximum likelihood estimate.
- Rank step in normalized coordinates. The closest rank 2 matrix is taken for , not for . In pixel coordinates the Frobenius norm has no good meaning.
Variants and improvements
- Anisotropic scaling. Scale and separately so that each has unit variance. This is a common alternative; the isotropic form of lines L1 and L2 is the usual choice.
- Essential matrix. For calibrated cameras, run the essential variant on normalized image coordinates ; those are already small and centered for most cameras, so the extra similarity matters less.
- Seven points. The same normalization is used by the seven-point algorithm, which forces exactly.
- Geometric refinement. Use the output to start a minimization of the Sampson distance or of the reprojection error. This is the Gold Standard method in Hartley and Zisserman.
- Inside RANSAC. Use the seven-point algorithm as the minimal solver in RANSAC, and then the normalized eight-point algorithm on all inliers.
When to use it
Use it whenever a fundamental matrix must be found linearly from eight or more pixel matches: on the inliers of a robust fit, as the start of a nonlinear refinement, or alone when moderate accuracy is enough. There is no reason to run the plain algorithm on pixel data. For calibrated cameras and data with outliers, the five-point algorithm in RANSAC is usually the better first step.
Pitfalls
- One similarity for both images. Each image needs its own from its own points.
- The rank step after denormalizing. Forcing rank 2 on in pixels, instead of on , loses much of the gain.
- Wrong side of the transpose. Line L10 is , not ; the fundamental matrix maps points to lines, so it changes by the transpose on the left.
- All points equal. The mean distance is then 0 and the similarity is not defined. Check for this before line L1.
- Degenerate scenes. Normalization does not fix planar scenes or pure rotations, where has rank at most 6.
- Outliers. The least squares fit has no robustness. Use it inside or after RANSAC.
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()
normalized_eight_point_algorithm.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/normalized-eight-point-algorithm/. The authors are listed in prov/6HV01C.jsonl.
"""Hartley's normalized eight-point algorithm for the fundamental matrix.
Given n >= 8 point pairs x1[i] <-> x2[i] (pixels, 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 image first gets its own similarity T1
or T2 that moves the centroid of its points to the origin and makes their
mean distance to it sqrt(2). The plain eight-point algorithm then runs on
the moved points, the rank 2 condition is forced there, and the result is
mapped back by F = T2^T F_hat T1.
The result has Frobenius norm 1, and its entry of largest absolute value is
positive. Cost: O(n) in total, because the SVD of the n x 9 matrix has a
fixed number of columns. With normalize=False the function is the plain
eight-point algorithm, kept here for comparison.
"""
from __future__ import annotations
import math
from typing import List, Sequence
from cvla import eye, matvec, mul, norm, nullvec, scale, svd, transpose
Matrix = List[List[float]]
def normalizing_similarity(pts: Sequence[Sequence[float]]) -> Matrix:
"""The 3 x 3 similarity T that moves the centroid of the points to the
origin and scales them so that their mean distance to it is sqrt(2).
Precondition: the points are not all equal. Cost O(n)."""
n = len(pts)
cx = sum(float(p[0]) for p in pts) / n
cy = sum(float(p[1]) for p in pts) / n
d = sum(math.hypot(float(p[0]) - cx, float(p[1]) - cy) for p in pts) / n
if d == 0.0:
raise ValueError("all points coincide")
s = math.sqrt(2.0) / d
return [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]]
def epipolar_row(y1: Sequence[float], y2: Sequence[float]) -> List[float]:
"""The row of A for one pair of homogeneous points: the Kronecker product
of y2 and y1, so that row . f = y2^T F y1 for F stored row by row."""
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 normalized_eight_point(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]],
normalize: bool = True) -> Matrix:
"""F from n >= 8 pairs of points (u, v), in canonical form."""
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")
T1 = normalizing_similarity(x1) if normalize else eye(3) # @line L1
T2 = normalizing_similarity(x2) if normalize else eye(3) # @line L2
a = []
for i in range(n): # @line L3
y1 = matvec(T1, [float(x1[i][0]), float(x1[i][1]), 1.0]) # @line L4
y2 = matvec(T2, [float(x2[i][0]), float(x2[i][1]), 1.0]) # @line L4
a.append(epipolar_row(y1, y2)) # @line L5
f = nullvec(a) # @line L6
G = [f[0:3], f[3:6], f[6:9]] # @line L7
u, s, v = svd(G) # @line L8
G = mul(mul(u, [[s[0], 0.0, 0.0], [0.0, s[1], 0.0], [0.0, 0.0, 0.0]]), transpose(v)) # @line L9
F = mul(mul(transpose(T2), G), T1) # @line L10
return canonical(F) # @line L11
def epipolar_distances(F: Sequence[Sequence[float]], x1: Sequence[Sequence[float]],
x2: Sequence[Sequence[float]]) -> List[float]:
"""For each pair, the distance in pixels from x2 to the epipolar line
F x1 in image 2."""
out = []
for p, q in zip(x1, x2):
line = matvec(F, [p[0], p[1], 1.0])
out.append(abs(line[0] * q[0] + line[1] * q[1] + line[2]) / math.hypot(line[0], line[1]))
return out
test_normalized_eight_point_algorithm.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/normalized-eight-point-algorithm/. The authors are listed in prov/6HV01C.jsonl.
"""Tests of the normalized eight-point algorithm."""
import math
import random
import pytest
from cvla import inv, matvec, mul, norm, skew, sub, svd, transpose
from normalized_eight_point_algorithm import (canonical, epipolar_distances,
epipolar_row,
normalized_eight_point,
normalizing_similarity)
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]]
def rotation(axis, angle):
"""Rodrigues formula, written out."""
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 two_views(rng, n):
"""A random relative pose and n pixel pairs of points in front of both
cameras. Returns R, t, x1, x2."""
R = rotation([rng.uniform(-1, 1) for _ in range(3)], rng.uniform(0.05, 0.3))
t = [rng.uniform(-1, 1), rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3)]
x1, x2 = [], []
while len(x1) < n:
X1 = [rng.uniform(-2.0, 2.0), rng.uniform(-2.0, 2.0), rng.uniform(4.0, 8.0)]
X2 = [a + b for a, b in zip(matvec(R, X1), t)]
if X2[2] > 0.5:
x1.append(project(K1, X1))
x2.append(project(K2, X2))
return R, t, x1, x2
def true_F(R, t):
return canonical(mul(mul(transpose(inv(K2)), mul(skew(t), R)), inv(K1)))
def noisy(rng, pts, sigma):
return [[c + rng.gauss(0.0, sigma) for c in p] for p in pts]
def test_similarity_values():
T = normalizing_similarity([[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]])
s = math.sqrt(2.0) / math.sqrt(2.0)
assert T == [[s, 0.0, -s], [0.0, s, -s], [0.0, 0.0, 1.0]]
pts = [[3.0, 1.0], [7.0, 4.0], [-2.0, 5.0], [0.0, 0.0]]
T = normalizing_similarity(pts)
ys = [matvec(T, [p[0], p[1], 1.0]) for p in pts]
assert abs(sum(y[0] for y in ys)) <= 1e-12 and abs(sum(y[1] for y in ys)) <= 1e-12
assert abs(sum(math.hypot(y[0], y[1]) for y in ys) / 4 - math.sqrt(2.0)) <= 1e-12
@pytest.mark.parametrize("seed", [1, 2, 3])
def test_exact_recovery(seed):
rng = random.Random(seed)
R, t, x1, x2 = two_views(rng, 15)
F = normalized_eight_point(x1, x2)
assert norm(sub(F, true_F(R, t))) <= 1e-8
s = svd(F)[1]
assert s[2] <= 1e-12
assert max(epipolar_distances(F, x1, x2)) <= 1e-8
def test_rectified_pair():
# Pure translation along +X with equal K: F ~ [[0,0,0],[0,0,-1],[0,1,0]].
rng = random.Random(4)
x1, x2 = [], []
for _ in range(10):
X = [rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(4, 8)]
x1.append(project(K1, X))
x2.append(project(K1, [X[0] - 0.5, X[1], X[2]]))
F = normalized_eight_point(x1, x2)
r = 1.0 / math.sqrt(2.0)
assert norm(sub(F, [[0.0, 0.0, 0.0], [0.0, 0.0, -r], [0.0, r, 0.0]])) <= 1e-8 or \
norm(sub(F, [[0.0, 0.0, 0.0], [0.0, 0.0, r], [0.0, -r, 0.0]])) <= 1e-8
def test_covariant_under_similarities():
# Moving each image by a similarity S gives S2^-T F S1^-1, even with noise.
rng = random.Random(5)
_, _, x1, x2 = two_views(rng, 20)
x1, x2 = noisy(rng, x1, 1.0), noisy(rng, x2, 1.0)
F = normalized_eight_point(x1, x2)
def sim(angle, s, tx, ty):
c, d = s * math.cos(angle), s * math.sin(angle)
return [[c, -d, tx], [d, c, ty], [0.0, 0.0, 1.0]]
S1, S2 = sim(0.7, 2.5, 100.0, -40.0), sim(-1.2, 0.3, -7.0, 900.0)
m1 = [matvec(S1, [p[0], p[1], 1.0])[:2] for p in x1]
m2 = [matvec(S2, [p[0], p[1], 1.0])[:2] for p in x2]
G = normalized_eight_point(m1, m2)
expected = canonical(mul(mul(transpose(inv(S2)), F), inv(S1)))
assert norm(sub(G, expected)) <= 1e-8
def test_normalization_improves_conditioning():
rng = random.Random(6)
_, _, x1, x2 = two_views(rng, 30)
plain = [epipolar_row([p[0], p[1], 1.0], [q[0], q[1], 1.0]) for p, q in zip(x1, x2)]
T1, T2 = normalizing_similarity(x1), normalizing_similarity(x2)
moved = [epipolar_row(matvec(T1, [p[0], p[1], 1.0]), matvec(T2, [q[0], q[1], 1.0]))
for p, q in zip(x1, x2)]
sp, sn = svd(plain)[1], svd(moved)[1]
# ratio of the largest to the second smallest singular value
assert sp[0] / sp[7] > 1e4
assert sn[0] / sn[7] < 1e2
def test_more_accurate_than_plain_under_noise():
# sigma = 1 pixel, 30 points, 10 scenes: mean distance in pixels of the
# noise-free points to the estimated epipolar lines.
rng = random.Random(10)
dn, dp = 0.0, 0.0
for _ in range(10):
_, _, x1, x2 = two_views(rng, 30)
n1, n2 = noisy(rng, x1, 1.0), noisy(rng, x2, 1.0)
dn += sum(epipolar_distances(normalized_eight_point(n1, n2), x1, x2)) / 300.0
dp += sum(epipolar_distances(normalized_eight_point(n1, n2, normalize=False), x1, x2)) / 300.0
assert dn < 1.0
assert dp > 2.0 * dn
def test_rejects_bad_input():
with pytest.raises(ValueError):
normalized_eight_point([[0.0, 0.0]] * 7, [[1.0, 1.0]] * 7)
with pytest.raises(ValueError):
normalized_eight_point([[0.0, 0.0]] * 8, [[1.0, 1.0]] * 8)
History
The eight-point algorithm of Longuet-Higgins (1981) was long held to be very sensitive to noise, and iterative methods were preferred. Hartley (1997), in a paper titled "In defense of the eight-point algorithm", showed that the poor results came from the bad condition of the linear system on pixel coordinates, and that translating and scaling the points first gives results close to those of iterative methods in his tests. The same idea applies to other linear estimates, such as the DLT for homographies. Hartley and Zisserman (2000, second edition 2004) present the normalized eight-point algorithm in Section 11.2.
References
- Richard I. Hartley, In defense of the eight-point algorithm, IEEE Transactions on Pattern Analysis and Machine Intelligence 19(6), 1997, 580-593, the isotropic normalization of the points, the condition of the linear system, and the comparison with iterative methods
- Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 11.2, The normalized 8-point algorithm
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 11.3, Two-frame structure from motion (the normalized eight-point algorithm)
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 6HV01C Edit this page History Report an error Markdown