Algorithmadvanced
Seven-point algorithm
Also called seven-point fundamental matrix solver.
Estimate the fundamental matrix from seven matches by taking the 2D null space of the linear system and solving the cubic det F = 0, giving one or three solutions.
- Solves
- Relative pose estimation
- Time
- Θ(1) worst · average · best
- Space
- Θ(1) extra
- Where
- n = the number of point pairs, fixed at 7
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ludwig Otto Hesse, Rudolf Sturm, Richard Hartley, 1869
The seven-point algorithm finds the fundamental matrix from exactly seven point matches, the fewest that fix it. Seven matches give seven linear equations in the nine entries of , so the solutions form a two-dimensional space spanned by two matrices and . The condition , which every fundamental matrix satisfies, is a cubic equation on the line through them. Each real root gives one fundamental matrix, so there are one or three. It is the standard minimal solver for inside RANSAC, because it needs fewer matches than the eight-point algorithm and it gives matrices of rank 2 exactly.
In plain words
Each match gives one equation for the nine unknown numbers of the matrix, and the overall size of the matrix does not matter. With eight matches the answer is fixed. With seven, there is one direction of freedom left: every mix of two particular matrices fits all seven matches. But a true fundamental matrix must also flatten one direction to nothing, and this adds one more equation. On the line of mixes that equation is a cubic, so it has one or three real roots. Each root is one candidate matrix. A robust method such as RANSAC then checks each candidate against the other matches.
The problem
Input. Seven point pairs as 2D points , extended to .
Output. The list of all real matrices with and for , each scaled to with its entry of largest absolute value positive. For points in general position the list has one or three entries; a double root of the cubic can give fewer distinct entries. If the pairs are exact images of points in general position seen by two cameras with different centers, the true is in the list.
The algorithm
SEVEN-POINT(x1_1 .. x1_7, x2_1 .. x2_7)- 1
T1, T2 <- the normalizing similarities of the points of image 1 and of image 2 - 2
A <- the 7 x 9 matrix with rows (y2[1] y1^T, y2[2] y1^T, y2[3] y1^T) for y1 = T1 x1_i and y2 = T2 x2_i - 3
F1, F2 <- the 3 x 3 matrices of two right singular vectors that span the null space of A - 4
(c3, c2, c1, c0) <- the coefficients of det(F2 + a (F1 - F2)) = c3 a^3 + c2 a^2 + c1 a + c0 - 5
for each real root a of this polynomial (of degree 2 if c3 = 0) - 6
append F2 + a (F1 - F2) to S - 7
if c3 = 0 then append F1 - F2 to S - 8
return the canonical forms of T2^T G T1 for all G in S
Line L1 is Hartley normalization, and line L2 builds the rows of the eight-point algorithm on the normalized points. If has rank 7, line L3 takes the two right singular vectors of the two zero singular values; if the rank is lower the points are degenerate, and the implementation stops with an error. Every matrix in the null space is . Up to scale these are for a real , plus the one direction that this form misses. The determinant of a matrix is a cubic in its entries, so line L4 can find the four coefficients from the values at :
Its leading coefficient is . When it is zero, itself has rank 2 and line L7 adds it. Line L8 undoes the normalization as in the normalized eight-point algorithm.
Example
Lines L4 to L7 act on any pair , . Take and , so .
| line | value |
|---|---|
| L4 | , , , ; the coefficients are , that is |
| L5 | roots , , |
| L6 | , , |
| L7 | , nothing added |
Two other cases show the other branches. With and the determinant is , which has one real root, , and the only solution is . With and the determinant is , so ; line L5 gives and , and line L7 adds .
On real data the count varies with the scene. For 40 random scenes of seven points seen by two cameras, the solver gave three solutions 34 times and one solution 6 times, and the true was always in the list.
Correctness
On exact data the true satisfies the seven linear equations, so it is in the null space of , and it has rank 2, so it is a root of the cubic or the direction . Conversely, every matrix in the list satisfies the seven equations because it is in the null space, and it has determinant 0 by construction. The cubic has real coefficients, so it has one or three real roots counted with multiplicity, and the list has one or three entries. If has rank below 7, as for points on one plane, the null space is larger and the method does not apply. The full proof is below.
Proof: The seven-point algorithm returns every singular matrix in the two-dimensional solution space, and there are 1 or 3 of them over the realsfull
We use the notation of the page. The input is 7 pairs of 2D points, written as and . Lines L1 and L2 move them to and and build the matrix with rows . Two nonzero matrices are equal up to scale when one is a nonzero multiple of the other. We work in exact arithmetic; the remarks at the end deal with the two tolerances of the code.
Claim. Let have rank 7, and let not vanish on the whole null space of . Then: (a) the output is a list of matrices of rank at most 2 that satisfy for ; (b) every real matrix with and for all is equal up to scale to one of the outputs; (c) counted with multiplicity, the number of such matrices up to scale is 1 or 3.
Lemma 1 (the solution space). If has rank 7, then the matrices with for all are exactly , , where and are the matrices of line L3.
Proof. By Lemma 1 of the eight-point proof, the constraints say . The null space of has dimension . The code pads with two zero rows and takes the SVD. The right singular vectors of the two smallest singular values, which are both 0, are orthonormal and lie in the null space, so they span it.
Lemma 2 (the projective line of solutions). Every nonzero is equal up to scale to exactly one of the matrices , , or to .
Proof. If , then with . If , then with . The matrices and are linearly independent, so different give matrices that are not equal up to scale, and no is a multiple of .
Lemma 3 (the cubic). is a polynomial of degree at most 3, , with and . Line L4 computes its coefficients exactly from the values at :
Proof. Each entry of has degree at most 1 in , and the determinant is a sum of products of three entries, so has degree at most 3. Write . The coefficient of comes from taking the part of every entry, which gives , and . For the formulas: and , which give and the odd sum . Next , so , which gives , and then .
Proof of part (a). Every output is , scaled, where is for a real root of (line L6), or when (line L7). In both cases (for because ), so has rank at most 2, and because and are independent. lies in the null space of by Lemma 1. By Lemma 1 of the normalized eight-point proof, has the same rank and satisfies the constraints on the input points. Line L8 only scales it.
Proof of part (b). Let be such a matrix and put . Then , , and satisfies the constraints on the moved points, so by Lemma 1 it is in the span of and . By Lemma 2 it is equal up to scale to some or to . In the first case and is real, so line L5 finds and line L6 adds . In the second case , so , and line L7 adds . Line L8 maps the matrix back to a multiple of .
Proof of part (c). We count the solutions on the projective line of Lemma 2, with multiplicity: a real root of counts with its multiplicity as a root, and the point counts times. This is the count of the roots of the homogeneous cubic on the projective line, which is not identically zero by hypothesis. If , a real cubic has 1 or 3 real roots counted with multiplicity, because its complex roots that are not real come in conjugate pairs. If , the real roots number 0 or 2, and adds 1. If , there is 1 real root and counts twice. If , then is a nonzero constant and counts three times. In every case the total is 1 or 3.
Remark (the true matrix). If the points are exact images under two cameras with fundamental matrix , then is real, has rank 2 and satisfies the constraints, so by part (b) it is among the outputs. The other outputs satisfy the same seven constraints, and seven pairs alone cannot tell them apart; an eighth pair or a consensus test is needed.
Remark (tolerances). The code stops with an error when , which is its test of the hypothesis that has rank 7. It treats as 0 when . In floating point both tests are thresholds, so near the boundary a solution close to can be reported as itself, or as a root of large absolute value. The real roots come from the helper polyroots_real, which returns the roots whose imaginary part is below its tolerance; a double root may then appear once or twice.
Complexity
The input size is fixed, so the time and space are . The work is one SVD of a matrix, four determinants and the roots of one cubic, which can be found in closed form or by a few steps of an iterative root finder. The cost is small and fixed, which matters because RANSAC calls it many times. For an inlier ratio of 0.5 and 99% confidence, the iteration bound is 588 samples of seven, against 1177 samples of eight.
Properties
- Minimal. Seven is the least number of matches that fixes up to a finite number of choices, since has 7 degrees of freedom.
- Rank 2 exactly. Every output has up to rounding, unlike the linear eight-point result before its rank step.
- One or three solutions. The count of real roots of a real cubic is one or three with multiplicity. All of them fit the seven matches, so other matches are needed to choose.
- Covariant under similarities. Like the normalized eight-point algorithm, because of the normalization of line L1.
- No least squares. It uses exactly seven matches. With more matches, use the eight-point algorithm or a robust method.
Variants and improvements
- Without normalization. Lines L1 and L8 can be skipped; the result is then less accurate on pixel data.
- Closed form roots. Cardano's formula gives the roots of the cubic directly; an iterative solver with a check for real roots is often more stable.
- Sturm sequences. A Sturm sequence counts the real roots in an interval before they are found.
- Degeneracy check. DEGENSAC (Chum, Werner and Matas 2005) tests whether five or more of the seven matches are related by one homography, which is a sign of a dominant plane, and then estimates from the plane and two more points.
- Calibrated cameras. If is known, the five-point algorithm needs fewer matches and finds the essential matrix directly.
When to use it
Use the seven-point algorithm as the minimal solver for the fundamental matrix inside RANSAC or its variants, when the cameras are not calibrated. Test each of the one or three solutions against all matches and keep the one with the most inliers. Then estimate again from all inliers with the normalized eight-point algorithm or a geometric fit.
Pitfalls
- Only one solution kept. All real roots are valid candidates; the true may be any of them.
- The missed direction. If , the form does not reach , which is a solution. A test with a tolerance is needed, since is rarely exactly zero in floating point.
- Planar points. If the seven points lie on one plane, has rank at most 6 and the null space has dimension 3 or more. Detect this from the singular values.
- Complex roots. A root with a small imaginary part from rounding can be a true solution. Decide with a tolerance, not by an exact test.
- Noise. Seven noisy matches give a noisy . Use the result only to find inliers, not as the final answer.
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()
seven_point_algorithm.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/seven-point-algorithm/. The authors are listed in prov/JZGDM0.jsonl.
"""The seven-point algorithm for the fundamental matrix.
Given exactly 7 point pairs x1[i] <-> x2[i] (pixels, 2 entries each), find
every 3 x 3 matrix F of rank 2 with x2[i]^T F x1[i] = 0. The 7 linear
equations leave a pencil of matrices F2 + alpha (F1 - F2); the condition
det F = 0 is a cubic in alpha, so there are 1 or 3 real solutions (and the
extra solution F1 - F2 when the cubic drops to a lower degree).
Each image first gets the Hartley similarity, as in the normalized eight-point
algorithm; the solutions are mapped back at the end. Every output has
Frobenius norm 1, and its entry of largest absolute value is positive.
Cost: O(1), because the input size is fixed.
"""
from __future__ import annotations
import math
from typing import List, Sequence
from cvla import det, matvec, mul, norm, polyroots_real, scale, svd, transpose
Matrix = List[List[float]]
LEADING_TOL = 1e-10
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)."""
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 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 _combine(F1: Matrix, F2: Matrix, alpha: float) -> Matrix:
"""F2 + alpha (F1 - F2)."""
return [[b + alpha * (a - b) for a, b in zip(r1, r2)] for r1, r2 in zip(F1, F2)]
def cubic_coefficients(F1: Matrix, F2: Matrix) -> List[float]:
"""[c3, c2, c1, c0] with det(F2 + alpha (F1 - F2)) = c3 alpha^3 + ... + c0,
found from the values at alpha = -1, 0, 1, 2 (the determinant is a cubic
in alpha, so 4 values fix it)."""
dm, d0, d1, d2 = (det(_combine(F1, F2, a)) for a in (-1.0, 0.0, 1.0, 2.0))
c0 = d0
c2 = 0.5 * (d1 + dm) - d0
odd = 0.5 * (d1 - dm) # c3 + c1
rest = d2 - 4.0 * c2 - c0 # 8 c3 + 2 c1
c3 = (rest - 2.0 * odd) / 6.0
c1 = odd - c3
return [c3, c2, c1, c0]
def pencil_solutions(F1: Matrix, F2: Matrix) -> List[Matrix]:
"""All matrices of rank at most 2 in the pencil spanned by F1 and F2."""
c = cubic_coefficients(F1, F2) # @line L4
big = max(abs(x) for x in c)
out = []
lead_zero = abs(c[0]) <= LEADING_TOL * big
for alpha in polyroots_real(c[1:] if lead_zero else c): # @line L5
out.append(_combine(F1, F2, alpha)) # @line L6
if lead_zero: # @line L7
out.append([[a - b for a, b in zip(r1, r2)] for r1, r2 in zip(F1, F2)]) # @line L7
return out
def seven_point(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]]) -> List[Matrix]:
"""All fundamental matrices for 7 pairs of points (u, v), in canonical
form. The list has 1, 2 or 3 entries for points in general position."""
if len(x1) != 7 or len(x2) != 7:
raise ValueError("need exactly 7 point pairs")
T1, T2 = normalizing_similarity(x1), normalizing_similarity(x2) # @line L1
a = []
for p, q in zip(x1, x2):
y1 = matvec(T1, [float(p[0]), float(p[1]), 1.0])
y2 = matvec(T2, [float(q[0]), float(q[1]), 1.0])
a.append([u * w for u in y2 for w in y1]) # @line L2
a += [[0.0] * 9, [0.0] * 9]
_, s, v = svd(a)
if s[6] <= 1e-10 * s[0]:
raise ValueError("degenerate configuration: the null space has dimension > 2")
f1 = [v[i][7] for i in range(9)] # @line L3
f2 = [v[i][8] for i in range(9)] # @line L3
F1 = [f1[0:3], f1[3:6], f1[6:9]]
F2 = [f2[0:3], f2[3:6], f2[6:9]]
result = []
for G in pencil_solutions(F1, F2):
result.append(canonical(mul(mul(transpose(T2), G), T1))) # @line L8
return result
test_seven_point_algorithm.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/seven-point-algorithm/. The authors are listed in prov/JZGDM0.jsonl.
"""Tests of the seven-point algorithm."""
import math
import random
import pytest
from cvla import inv, matvec, mul, norm, skew, sub, svd, transpose
from seven_point_algorithm import (canonical, cubic_coefficients,
pencil_solutions, seven_point)
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 diag(a, b, c):
return [[a, 0.0, 0.0], [0.0, b, 0.0], [0.0, 0.0, c]]
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, planar=False):
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)]
x1, x2 = [], []
while len(x1) < n:
x, y = rng.uniform(-2.0, 2.0), rng.uniform(-2.0, 2.0)
X1 = [x, y, 6.0 + 0.3 * x - 0.2 * y if planar else 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 contains(sols, M, tol):
M = canonical(M)
return any(norm(sub(canonical(S), M)) <= tol for S in sols)
def test_cubic_with_three_real_roots():
# F2 + alpha (F1 - F2) = diag(1 + alpha, 2 - alpha, 3 - 3 alpha)
F1, F2 = diag(2.0, 1.0, 0.0), diag(1.0, 2.0, 3.0)
c = cubic_coefficients(F1, F2)
# det = 3 (1 + alpha)(2 - alpha)(1 - alpha) = 3 alpha^3 - 6 alpha^2 - 3 alpha + 6
assert max(abs(a - b) for a, b in zip(c, [3.0, -6.0, -3.0, 6.0])) <= 1e-12
sols = pencil_solutions(F1, F2)
assert len(sols) == 3
for M in (diag(0.0, 3.0, 6.0), diag(3.0, 0.0, -3.0), diag(2.0, 1.0, 0.0)):
assert contains(sols, M, 1e-12)
def test_cubic_with_one_real_root():
# det [[1, -a, 0], [a, 1, 0], [0, 0, 1 + a]] = (1 + a^2)(1 + a)
F2 = diag(1.0, 1.0, 1.0)
F1 = [[1.0, -1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 2.0]]
sols = pencil_solutions(F1, F2)
assert len(sols) == 1
assert contains(sols, [[1.0, 1.0, 0.0], [-1.0, 1.0, 0.0], [0.0, 0.0, 0.0]], 1e-12)
def test_leading_coefficient_zero_adds_the_direction():
# diag(1, 2 - alpha, 3 - 2 alpha): a quadratic, and F1 - F2 = diag(0, -1, -2)
F1, F2 = diag(1.0, 1.0, 1.0), diag(1.0, 2.0, 3.0)
sols = pencil_solutions(F1, F2)
assert len(sols) == 3
for M in (diag(1.0, 0.0, -1.0), diag(1.0, 0.5, 0.0), diag(0.0, -1.0, -2.0)):
assert contains(sols, M, 1e-12)
@pytest.mark.parametrize("seed", range(6))
def test_true_F_is_among_the_solutions(seed):
rng = random.Random(seed)
R, t, x1, x2 = two_views(rng, 7)
sols = seven_point(x1, x2)
assert len(sols) in (1, 3)
assert contains(sols, true_F(R, t), 1e-8)
for F in sols:
s = svd(F)[1]
assert s[2] <= 1e-10 * s[0]
for p, q in zip(x1, x2):
line = matvec(F, [p[0], p[1], 1.0])
d = abs(line[0] * q[0] + line[1] * q[1] + line[2]) / math.hypot(line[0], line[1])
assert d <= 1e-6 # pixels
def test_both_solution_counts_occur():
counts = set()
for seed in range(12):
_, _, x1, x2 = two_views(random.Random(seed), 7)
counts.add(len(seven_point(x1, x2)))
assert counts == {1, 3}
def test_planar_points_are_rejected():
_, _, x1, x2 = two_views(random.Random(20), 7, planar=True)
with pytest.raises(ValueError):
seven_point(x1, x2)
def test_wrong_number_of_points():
with pytest.raises(ValueError):
seven_point([[0.0, 0.0]] * 8, [[1.0, 1.0]] * 8)
History
The problem is old. Chasles posed the problem of seven pairs of points in the plane, and Hesse (1863) derived the cubic equation on which it depends. Sturm (1869) studied it in detail and showed that there are three solutions in general. In computer vision the same count appears as the number of fundamental matrices for seven matches, and Hartley and Zisserman (2000, second edition 2004) give the algorithm in its modern form, with the pencil and the cubic . It became the usual minimal solver for robust estimation of , and Chum, Werner and Matas (2005) added a test for its failure on scenes with a dominant plane.
References
- Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 11.1, Basic equations (the minimum case of seven point correspondences and the cubic in the pencil)
- Rudolf Sturm, Das Problem der Projectivität und seine Anwendung auf die Flächen zweiten Grades, Mathematische Annalen 1(4), 1869, 533-574, the problem of seven pairs of points and its three solutions
- Ludwig Otto Hesse, Die cubische Gleichung, von welcher die Lösung des Problems der Homographie von M. Chasles abhängt, Journal für die reine und angewandte Mathematik 62, 1863, the cubic equation of the seven point problem
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 JZGDM0 Edit this page History Report an error Markdown