Algorithm Search⌘K

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.

Time
Θ(n) worst · average · best
Space
Θ(n) extra
Where
n = the number of point pairs
Properties
deterministicexactofflineiterative
Origin
H. C. Longuet Higgins, Richard Hartley, 1981

The eight-point algorithm estimates the fundamental matrix FF, or the essential matrix EE of calibrated cameras, from n≥8n \ge 8 point matches. Each match x1↔x2\mathbf{x}_1 \leftrightarrow \mathbf{x}_2 gives the equation x2TFx1=0\mathbf{x}_2^{\mathsf T}F\mathbf{x}_1 = 0, which is linear in the nine entries of FF. The algorithm stacks these equations into an n×9n \times 9 matrix AA, takes the unit vector that makes ∥Af∥\|A\mathbf{f}\| 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 (x1,i,x2,i)(\mathbf{x}_{1,i}, \mathbf{x}_{2,i}), i=1,…,ni = 1, \ldots, n, n≥8n \ge 8, as 2D points (u,v)(u, v) that the algorithm extends to (u,v,1)T(u, v, 1)^{\mathsf T}. For the essential variant the points are in normalized image coordinates, x^=K−1x\hat{\mathbf{x}} = K^{-1}\mathbf{x}.

Output. A 3×33 \times 3 matrix FF of rank 2 (or with singular values (s,s,0)(s, s, 0) in the essential variant) with ∥F∥F=1\|F\|_F = 1 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

  1. EIGHT-POINT(x1_1 .. x1_n, x2_1 .. x2_n, essential)
  2. 1for i <- 1 to n
  3. 2append the row (u2 u1, u2 v1, u2, v2 u1, v2 v1, v2, u1, v1, 1) of the pair (x1_i, x2_i) to A
  4. 3f <- the right singular vector of A for its smallest singular value
  5. 4F0 <- the 3 x 3 matrix with rows f[1..3], f[4..6], f[7..9]
  6. 5(U, diag(s1, s2, s3), V) <- the SVD of F0
  7. 6F <- U diag(s1, s2, 0) V^T, or U diag(m, m, 0) V^T with m = (s1 + s2) / 2 if essential
  8. 7return 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 (u2,v2,1)(u_2, v_2, 1) and (u1,v1,1)(u_1, v_1, 1), so that its dot product with f\mathbf{f}, the entries of FF row by row, is x2TFx1\mathbf{x}_2^{\mathsf T}F\mathbf{x}_1. Line L3 minimizes ∥Af∥\|A\mathbf{f}\| over unit vectors by the singular value decomposition. On exact data AA has rank 8 and f\mathbf{f} spans its null space. Line L6 replaces F0F_0 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 λF\lambda F so that equal results compare equal.

Example

Take the pose of the running example of epipolar geometry: R=(0.800.6010−0.600.8)R = \begin{pmatrix} 0.8 & 0 & 0.6 \\ 0 & 1 & 0 \\ -0.6 & 0 & 0.8 \end{pmatrix}, t=(1,0,0)\mathbf{t} = (1, 0, 0), X2=RX1+t\mathbf{X}_2 = R\mathbf{X}_1 + \mathbf{t}, and E=[t]×R=(0000.60−0.8010)E = [\mathbf{t}]_\times R = \begin{pmatrix} 0 & 0 & 0 \\ 0.6 & 0 & -0.8 \\ 0 & 1 & 0 \end{pmatrix}. The eight points X1\mathbf{X}_1 are (0,0,5)(0, 0, 5), (1,1,4)(1, 1, 4), (−1,2,6)(-1, 2, 6), (2,−1,5)(2, -1, 5), (−2,−2,8)(-2, -2, 8), (1,−2,4)(1, -2, 4), (−1,−1,5)(-1, -1, 5) and (2,2,6)(2, 2, 6). In normalized coordinates the first two pairs are (0,0)↔(1,0)(0, 0) \leftrightarrow (1, 0) and (14,14)↔(2113,513)(\frac14, \frac14) \leftrightarrow (\frac{21}{13}, \frac{5}{13}).

line value
L1, L2 8 rows; the row of pair 2 is (2152,2152,2113,552,552,513,14,14,1)(\frac{21}{52}, \frac{21}{52}, \frac{21}{13}, \frac{5}{52}, \frac{5}{52}, \frac{5}{13}, \frac14, \frac14, 1)
L3 the singular values of AA are 4.770,1.867,1.321,0.3244,0.2586,0.1355,0.03630,0.015614.770, 1.867, 1.321, 0.3244, 0.2586, 0.1355, 0.03630, 0.01561 and 0, so AA has rank 8 and f\mathbf{f} is the null vector
L4 F0=±E/2F_0 = \pm E/\sqrt2
L5 the singular values of F0F_0 are (0.70711,0.70711,0)(0.70711, 0.70711, 0)
L6 no change: F0F_0 already has rank 2 and two equal singular values
L7 (0000.424260−0.5656900.707110)=E/2\begin{pmatrix} 0 & 0 & 0 \\ 0.42426 & 0 & -0.56569 \\ 0 & 0.70711 & 0 \end{pmatrix} = E/\sqrt2

A check of pair 1: E(0,0,1)T=(0,−0.8,0)TE(0, 0, 1)^{\mathsf T} = (0, -0.8, 0)^{\mathsf T}, and its dot product with (1,0,1)(1, 0, 1) is 0. Now add 0.010.01 to v2v_2 of pair 4. Then AA has full rank, the singular values of F0F_0 are (0.71388,0.70023,0.0071020)(0.71388, 0.70023, 0.0071020), line L6 drops the third one, and line L7 gives singular values (0.71390,0.70025,0)(0.71390, 0.70025, 0). The essential variant gives (0.70711,0.70711,0)(0.70711, 0.70711, 0). The algebraic residuals x2TFx1\mathbf{x}_2^{\mathsf T}F\mathbf{x}_1 of the eight pairs are now about 0.0020.002 to 0.0130.013 instead of 0.

Correctness

The row of line L2 makes (Af)i=x2,iTFx1,i(A\mathbf{f})_i = \mathbf{x}_{2,i}^{\mathsf T}F\mathbf{x}_{1,i}. On exact data the true FF gives Af=0A\mathbf{f} = \mathbf{0}, and for eight or more points in general position AA has rank 8, so line L3 returns the true FF 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, AA 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 n≥8n \ge 8 pairs of 2D points, written as xi=(ui,vi,1)T\mathbf{x}_i = (u_i, v_i, 1)^{\mathsf T} in image 1 and xi′=(ui′,vi′,1)T\mathbf{x}'_i = (u'_i, v'_i, 1)^{\mathsf T} in image 2. For a 3×33 \times 3 matrix GG we write g∈R9\mathbf{g} \in \mathbb{R}^9 for its rows put one after the other, so ∥g∥=∥G∥F\|\mathbf{g}\| = \|G\|_F. The canonical form of a nonzero matrix GG is G/∥G∥FG / \|G\|_F 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 σ1≥σ2≥⋯\sigma_1 \ge \sigma_2 \ge \cdots.

Claim. (a) The vector f\mathbf{f} of line L3 minimizes ∥Af∥\|A\mathbf{f}\| over all unit vectors. (b) The matrix of line L6 is a matrix of rank at most 2 that is closest to F0F_0 in the Frobenius norm. In the essential variant, it is a matrix with singular values (m,m,0)(m, m, 0), m≥0m \ge 0, that is closest to F0F_0. (c) Let FF be a real 3×33 \times 3 matrix of rank 2 with xi′TFxi=0\mathbf{x}'^{\mathsf T}_i F\mathbf{x}_i = 0 for all ii, and let AA have rank 8. Then EIGHT-POINT returns the canonical form of FF. (d) If there is an invertible HH with xi′∼Hxi\mathbf{x}'_i \sim H\mathbf{x}_i for all ii (a planar scene, or a camera that only rotates), then AA has rank at most 6, so the hypothesis of (c) fails.

Lemma 1 (the row). For every 3×33 \times 3 matrix GG, the row aiT=(xi′⊗xi)T\mathbf{a}_i^{\mathsf T} = (\mathbf{x}'_i \otimes \mathbf{x}_i)^{\mathsf T} of line L2 satisfies aiTg=xi′TGxi\mathbf{a}_i^{\mathsf T}\mathbf{g} = \mathbf{x}'^{\mathsf T}_i G\mathbf{x}_i.

Proof. Entry 3(j−1)+k3(j - 1) + k of xi′⊗xi\mathbf{x}'_i \otimes \mathbf{x}_i is xi,j′xi,kx'_{i,j} x_{i,k}, and entry 3(j−1)+k3(j - 1) + k of g\mathbf{g} is GjkG_{jk}. So aiTg=∑j,kxi,j′Gjkxi,k=xi′TGxi\mathbf{a}_i^{\mathsf T}\mathbf{g} = \sum_{j,k} x'_{i,j} G_{jk} x_{i,k} = \mathbf{x}'^{\mathsf T}_i G\mathbf{x}_i. □\square

So Ag=0A\mathbf{g} = \mathbf{0} holds exactly when GG satisfies the epipolar constraint on all nn pairs.

Lemma 2 (minimum of the algebraic error). Let AA be an m×9m \times 9 real matrix and let σmin⁡≥0\sigma_{\min} \ge 0 be its smallest singular value, counted as 0 when m<9m < 9. Then min⁡∥f∥=1∥Af∥=σmin⁡\min_{\|\mathbf{f}\| = 1} \|A\mathbf{f}\| = \sigma_{\min}, and a right singular vector for σmin⁡\sigma_{\min} attains it.

Proof. Let ATA=Vdiag⁡(σ12,…,σ92)VTA^{\mathsf T}A = V \operatorname{diag}(\sigma_1^2, \ldots, \sigma_9^2) V^{\mathsf T} with VV orthogonal. For a unit vector f\mathbf{f} put c=VTf\mathbf{c} = V^{\mathsf T}\mathbf{f}, also a unit vector. Then ∥Af∥2=∑jσj2cj2≥σ92\|A\mathbf{f}\|^2 = \sum_j \sigma_j^2 c_j^2 \ge \sigma_9^2. The last column of VV gives c=e9\mathbf{c} = \mathbf{e}_9 and equality. □\square

Part (a) is Lemma 2 applied to line L3.

Lemma 3 (closest matrices with given singular value pattern). Let F0=Udiag⁡(s1,s2,s3)VTF_0 = U \operatorname{diag}(s_1, s_2, s_3) V^{\mathsf T} be an SVD. (i) Udiag⁡(s1,s2,0)VTU \operatorname{diag}(s_1, s_2, 0) V^{\mathsf T} is a matrix of rank at most 2 closest to F0F_0 in the Frobenius norm, at distance s3s_3. (ii) Among the matrices with singular values (m,m,0)(m, m, 0) for some m≥0m \ge 0, Udiag⁡(mˉ,mˉ,0)VTU \operatorname{diag}(\bar m, \bar m, 0) V^{\mathsf T} with mˉ=(s1+s2)/2\bar m = (s_1 + s_2)/2 is closest to F0F_0.

Proof. We use von Neumann's trace inequality: for real 3×33 \times 3 matrices PP and QQ with singular values pjp_j and qjq_j, tr⁡(PTQ)≤∑jpjqj\operatorname{tr}(P^{\mathsf T}Q) \le \sum_j p_j q_j. Let GG have singular values g1≥g2≥g3g_1 \ge g_2 \ge g_3. Then

∥F0−G∥F2=∥F0∥F2+∥G∥F2−2tr⁡(F0TG)≥∑j(sj−gj)2.\|F_0 - G\|_F^2 = \|F_0\|_F^2 + \|G\|_F^2 - 2\operatorname{tr}(F_0^{\mathsf T}G) \ge \sum_j (s_j - g_j)^2 .

For (i), g3=0g_3 = 0, so the bound is at least s32s_3^2, and G=Udiag⁡(s1,s2,0)VTG = U \operatorname{diag}(s_1, s_2, 0) V^{\mathsf T} gives ∥F0−G∥F=s3\|F_0 - G\|_F = s_3. For (ii), g=(m,m,0)g = (m, m, 0), and the bound (s1−m)2+(s2−m)2+s32(s_1 - m)^2 + (s_2 - m)^2 + s_3^2 is smallest at m=mˉm = \bar m. The matrix Udiag⁡(mˉ,mˉ,0)VTU \operatorname{diag}(\bar m, \bar m, 0) V^{\mathsf T} attains the bound, because F0−G=Udiag⁡(s1−mˉ,s2−mˉ,s3)VTF_0 - G = U \operatorname{diag}(s_1 - \bar m, s_2 - \bar m, s_3) V^{\mathsf T}. □\square

Lines L5 and L6 compute exactly these matrices, so part (b) is Lemma 3.

Proof of part (c). By Lemma 1, Aftrue=0A\mathbf{f}_{\mathrm{true}} = \mathbf{0} for the vector ftrue\mathbf{f}_{\mathrm{true}} of FF. The rank of AA is 8, so its null space is the line spanned by ftrue\mathbf{f}_{\mathrm{true}}, σ9=0\sigma_9 = 0 and σ8>0\sigma_8 > 0. By Lemma 2, line L3 returns a unit vector in this null space, so F0=λFF_0 = \lambda F with λ≠0\lambda \ne 0. Then F0F_0 has rank 2 and s3=0s_3 = 0, so line L6 gives F0F_0 back unchanged. Line L7 divides by ∥F0∥F=∣λ∣ ∥F∥F\|F_0\|_F = |\lambda|\,\|F\|_F 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 FF. In the essential variant, if FF has singular values (s,s,0)(s, s, 0), then s1=s2s_1 = s_2 for F0F_0 and line L6 again changes nothing. ■\blacksquare

Proof of part (d). Let xi′=κiHxi\mathbf{x}'_i = \kappa_i H\mathbf{x}_i with κi≠0\kappa_i \ne 0. For every a∈R3\mathbf{a} \in \mathbb{R}^3 put Ga=[a]×HG_{\mathbf{a}} = [\mathbf{a}]_\times H. Then xi′TGaxi=κi−1 xi′T(a×xi′)=0\mathbf{x}'^{\mathsf T}_i G_{\mathbf{a}}\mathbf{x}_i = \kappa_i^{-1}\,\mathbf{x}'^{\mathsf T}_i(\mathbf{a} \times \mathbf{x}'_i) = 0, because a×xi′\mathbf{a} \times \mathbf{x}'_i is orthogonal to xi′\mathbf{x}'_i. The map a↦[a]×H\mathbf{a} \mapsto [\mathbf{a}]_\times H is linear and one to one, because HH is invertible and [a]×=0[\mathbf{a}]_\times = 0 only for a=0\mathbf{a} = \mathbf{0}. By Lemma 1 its image, a space of dimension 3, lies in the null space of AA. So AA has rank at most 9−3=69 - 3 = 6. If the camera only rotates, xi′∼K′RK−1xi\mathbf{x}'_i \sim K' R K^{-1}\mathbf{x}_i, which is the same case with H=K′RK−1H = K' R K^{-1}. ■\blacksquare

Remark (what the proof does not give). On noisy data the output minimizes the algebraic error ∑i(xi′TF0xi)2\sum_i (\mathbf{x}'^{\mathsf T}_i F_0\mathbf{x}_i)^2 under ∥F0∥F=1\|F_0\|_F = 1, 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 AA 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 Θ(n)\Theta(n) and builds an n×9n \times 9 matrix. The SVD of a matrix with a fixed number of 9 columns costs Θ(n)\Theta(n): a QR decomposition reduces it to a 9×99 \times 9 triangle in Θ(n)\Theta(n), and the rest takes a fixed amount of work. Lines L4 to L7 work on 3×33 \times 3 matrices and cost Θ(1)\Theta(1). So the time is Θ(n)\Theta(n) in all cases, and the extra space is Θ(n)\Theta(n) for AA; a version that keeps only ATAA^{\mathsf T}A needs Θ(1)\Theta(1) but squares the condition number.

In floating point the accuracy depends on the condition of AA. With pixel coordinates the nine columns have sizes from about 10510^5 (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 10610^6 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 n×9n \times 9 matrix and one of a 3×33 \times 3 matrix.
  • Algebraic, not geometric. On noisy data line L3 minimizes ∑i(x2,iTFx1,i)2\sum_i (\mathbf{x}_{2,i}^{\mathsf T}F\mathbf{x}_{1,i})^2, 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 FTF^{\mathsf T}.

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 (m,m,0)(m, m, 0). The pose then comes from essential matrix decomposition.
  • Seven points. With seven matches AA has a two-dimensional null space, and det⁡F=0\det F = 0 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, AA 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 x2TFx1=0\mathbf{x}_2^{\mathsf T}F\mathbf{x}_1 = 0. The other order of the images needs FTF^{\mathsf T}.
  • Sign and scale. FF and −F-F 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.

cvla.pyI0RawGitHub
# 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 AA 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

  1. 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
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example