Algorithm Search⌘K

Algorithmadvanced

Five-point algorithm

Also called Nister five-point algorithm, five-point relative pose solver.

Find the up to ten essential matrices consistent with five calibrated matches by solving a polynomial of degree 10 built from the cubic essential matrix constraints.

Time
Θ(n) worst · average · best
Space
Θ(n) extra
Where
n = the number of point pairs, at least 5
Properties
deterministicexactofflineiterative
Origin
David Nister, Michel Demazure, Olivier Faugeras, Stephen Maybank, 2004

The five-point algorithm finds every essential matrix that fits five point matches between two calibrated views. Five is the fewest matches that fix the relative pose up to a finite number of choices, because EE has five degrees of freedom. Five linear epipolar equations leave a four-dimensional space E=xX+yY+zZ+WE = xX + yY + zZ + W. The cubic constraints of the characterization theorem then give ten equations in xx, yy, zz, which Nister (2004) reduced to one polynomial of degree 10 in zz. There are at most 10 solutions, as Demazure (1988) showed, and in practice often 2 to 4 of them are real. It is the standard minimal solver for the relative pose problem inside RANSAC.

In plain words

When the cameras are calibrated, the motion between two views has five unknowns: three for the turn and two for the direction of travel. Each matched point gives one equation, so five matches should be enough. The equations from the matches are simple, but they leave four candidate matrices that can be mixed in any way. Only special mixes are true motion matrices, and the test for that is a set of equations of the third power. The algorithm eliminates unknowns step by step until one equation in one unknown is left, of the tenth power. Each real root of it gives one candidate motion. A robust method then checks the candidates against the other matches.

The problem

Input. Five point pairs (x^1,i,x^2,i)(\hat{\mathbf{x}}_{1,i}, \hat{\mathbf{x}}_{2,i}) in normalized image coordinates x^=K−1(u,v,1)T\hat{\mathbf{x}} = K^{-1}(u, v, 1)^{\mathsf T}, given by their first two entries. The implementation also accepts n>5n > 5 pairs and then uses the four-dimensional space of least algebraic error.

Output. The list of real essential matrices EE with x^2,iTEx^1,i=0\hat{\mathbf{x}}_{2,i}^{\mathsf T}E\hat{\mathbf{x}}_{1,i} = 0 for all five pairs, each with ∥E∥F=1\|E\|_F = 1 and its entry of largest absolute value positive. It has at most 10 entries. For exact matches of points in general position, the true EE is in the list.

The algorithm

  1. FIVE-POINT(x1_1 .. x1_5, x2_1 .. x2_5)
  2. 1A <- the 5 x 9 matrix with rows (x2[1] x1^T, x2[2] x1^T, x2[3] x1^T) for the pairs (x1_i, x2_i)
  3. 2X, Y, Z, W <- the 3 x 3 matrices of four right singular vectors that span the null space of A
  4. 3M <- the 10 x 20 matrix of coefficients of det E = 0 and 2 E E^T E - tr(E E^T) E = 0 for E = x X + y Y + z Z + W
  5. 4split M into its first 10 columns P and its last 10 columns Q
  6. 5C <- P^-1 Q, so that the reduced system is [I | C]
  7. 6B(z) <- the 3 x 3 matrix of polynomials in z with rows: row 5 - z row 6, row 7 - z row 8, row 9 - z row 10 of [I | C]
  8. 7for each real root z of det B(z)
  9. 8(x, y, 1) <- the cross product of two rows of B(z), the pair with the largest result, divided by its last entry
  10. 9polish (x, y, z) by Gauss-Newton steps on the ten cubic equations
  11. 10append the canonical form of x X + y Y + z Z + W to the list
  12. 11return the list

The 20 columns of MM are the monomials of degree at most 3 in xx, yy, zz, in Nister's order: first x3,y3,x2y,xy2,x2z,x2,y2z,y2,xyz,xyx^3, y^3, x^2y, xy^2, x^2z, x^2, y^2z, y^2, xyz, xy, then xz2,xz,x,yz2,yz,y,z3,z2,z,1xz^2, xz, x, yz^2, yz, y, z^3, z^2, z, 1. The scale of EE is fixed by setting the weight of WW to 1. Line L5 is Gauss-Jordan elimination; for data in general position the left block is invertible. Rows 5 and 6 of the reduced system have leading monomials x2zx^2z and x2x^2, so row 5 minus zz times row 6 has no term of degree 3 in xx and yy together; the same holds for rows 7 and 8 (y2zy^2z and y2y^2) and rows 9 and 10 (xyzxyz and xyxy). What is left in each new row is xx times a polynomial in zz of degree at most 3, yy times one of degree at most 3, and one of degree at most 4. So B(z)(x,y,1)T=0B(z)(x, y, 1)^{\mathsf T} = \mathbf{0}, and a solution needs det⁡B(z)=0\det B(z) = 0, a polynomial of degree at most 3+3+4=103 + 3 + 4 = 10. Line L8 finds the null vector of B(z)B(z) from its rows. Line L9 is an addition of this implementation and not part of Nister's method: a step is kept only if it reduces the residual of the ten equations, and it restores the digits lost when two roots of det⁡B(z)\det B(z) are close.

Example

Take the first five pairs of the eight-point example: the true pose is 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), and the true essential matrix in canonical form is E/2=(0000.424260−0.5656900.707110)E/\sqrt2 = \begin{pmatrix} 0 & 0 & 0 \\ 0.42426 & 0 & -0.56569 \\ 0 & 0.70711 & 0 \end{pmatrix}.

line value
L1, L2 AA is 5×95 \times 9 of rank 5, and X,Y,Z,WX, Y, Z, W span its null space
L3 to L5 MM is 10×2010 \times 20, and its left 10×1010 \times 10 block is invertible
L6, L7 det⁡B(z)\det B(z) has four real roots: −19.22-19.22, 1.69681.6968, 1.70311.7031 and 561.9561.9
L8 four triples (x,y,z)(x, y, z); for the root 1.69681.6968, which is close to 1.70311.7031, the matrix has third singular value 6.7×10−66.7 \times 10^{-6} instead of 0
L9 after the polish, the third singular value of every solution is below 10−1610^{-16}
L10, L11 four essential matrices, one of which is E/2E/\sqrt2

All four fit the five matches exactly. The other three matches of the eight-point example, or the test of cheirality after decomposition, single out the true one. Over 60 random scenes the distance of the closest solution to the true EE was at most 2.4×10−122.4 \times 10^{-12}.

Correctness

Every essential matrix that fits the five matches lies in the null space of AA, so it is xX+yY+zZ+wWxX + yY + zZ + wW; for data in general position w≠0w \ne 0, and scaling gives w=1w = 1. By the characterization theorem it satisfies the ten cubic equations, so Mm=0M\mathbf{m} = \mathbf{0} for its vector of monomials m\mathbf{m}, and then [I∣C]m=0[I \mid C]\mathbf{m} = \mathbf{0} and B(z)(x,y,1)T=0B(z)(x, y, 1)^{\mathsf T} = \mathbf{0}. So its zz is a root of det⁡B(z)\det B(z), and when B(z)B(z) has rank 2 the null vector found at line L8 is its (x,y,1)(x, y, 1). Conversely each output satisfies the five linear equations and the ten cubics, and by the characterization theorem it is a real essential matrix. The polynomial has degree at most 10, so there are at most 10 solutions. The full proof is below.

Proof: Every essential matrix that fits five point pairs is a root of the degree 10 polynomial of the five-point algorithm, and the algorithm returns itfull

We use the notation of the page. The input is n≥5n \ge 5 pairs of points in normalized image coordinates, xi=(ui,vi,1)T\mathbf{x}_i = (u_i, v_i, 1)^{\mathsf T} and xi′=(ui′,vi′,1)T\mathbf{x}'_i = (u'_i, v'_i, 1)^{\mathsf T}. A real 3×33 \times 3 matrix is essential when it is [t]×R[\mathbf{t}]_\times R for a rotation RR and a vector t≠0\mathbf{t} \ne \mathbf{0}. We use the characterization theorem: a real 3×33 \times 3 matrix E≠0E \ne 0 is essential if and only if det⁡E=0\det E = 0 and 2EETE−tr⁡(EET)E=02EE^{\mathsf T}E - \operatorname{tr}(EE^{\mathsf T})E = 0. We work in exact arithmetic and with n=5n = 5; the remarks at the end deal with n>5n > 5, the polish of line L9 and the tolerances.

Hypotheses. (H1) The 5×95 \times 9 matrix AA of line L1 has rank 5. (H2) The left 10×1010 \times 10 block of the matrix MM of line L3 is invertible. (H3) The polynomial det⁡B(z)\det B(z) of line L7 is not identically zero. (H4) For each real root zz of det⁡B(z)\det B(z), the matrix B(z)B(z) has rank 2. These hold for points in general position, and the code reports nothing for a root where (H4) fails.

Claim. (a) Let EE be a real essential matrix with xi′TExi=0\mathbf{x}'^{\mathsf T}_i E\mathbf{x}_i = 0 for i=1,…,5i = 1, \ldots, 5, and suppose that EE is not in the span of XX, YY and ZZ. Then the canonical form of EE is one of the outputs. (b) Every output satisfies the five epipolar constraints. (c) The number of outputs is at most 10. (d) If, in addition, the five pairs have exactly 10 complex solutions with distinct values of zz, every output is an essential matrix, and the number of outputs is even.

Lemma 1 (the solution space). Under (H1), the real matrices GG with xi′TGxi=0\mathbf{x}'^{\mathsf T}_i G\mathbf{x}_i = 0 for all ii are exactly G=xX+yY+zZ+wWG = xX + yY + zZ + wW with (x,y,z,w)∈R4(x, y, z, w) \in \mathbb{R}^4.

Proof. By Lemma 1 of the eight-point proof, the constraints say Ag=0A\mathbf{g} = \mathbf{0}. The null space of AA has dimension 4. The code pads AA to 9 rows with zeros, and the right singular vectors of the four zero singular values are orthonormal and lie in the null space, so they span it. Line L2 takes them as XX, YY, ZZ and WW. □\square

If EE is not in the span of XX, YY and ZZ, then w≠0w \ne 0, and E/w=xX+yY+zZ+WE / w = xX + yY + zZ + W with new values of xx, yy and zz. So it is enough to find the solutions with w=1w = 1.

Lemma 2 (the ten cubics). For E(x,y,z)=xX+yY+zZ+WE(x, y, z) = xX + yY + zZ + W, the ten polynomials det⁡E\det E and the nine entries of 2EETE−tr⁡(EET)E2EE^{\mathsf T}E - \operatorname{tr}(EE^{\mathsf T})E have degree at most 3 in (x,y,z)(x, y, z). Let m\mathbf{m} be the vector of the 20 monomials of degree at most 3, in the order of the page. Then the ten polynomials are MmM\mathbf{m}, where row rr of MM holds the coefficients of polynomial rr.

Proof. Each entry of EE has degree at most 1. A determinant of a 3×33 \times 3 matrix and each entry of EETEEE^{\mathsf T}E are sums of products of three entries, and tr⁡(EET)E\operatorname{tr}(EE^{\mathsf T})E is a sum of products of two entries with one entry. So the degree is at most 3. There are exactly 20 monomials xaybzcx^a y^b z^c with a+b+c≤3a + b + c \le 3. □\square

So (x,y,z)(x, y, z) gives an essential matrix exactly when Mm(x,y,z)=0M\mathbf{m}(x, y, z) = \mathbf{0} (and E≠0E \ne 0, which holds because WW is not in the span of XX, YY and ZZ).

Lemma 3 (the reduced system). Under (H2), Mm=0M\mathbf{m} = \mathbf{0} is equivalent to [I∣C] m=0[I \mid C]\,\mathbf{m} = \mathbf{0}, where CC is the matrix of line L5. Write the right part of m\mathbf{m} as mR=(xz2,xz,x,yz2,yz,y,z3,z2,z,1)\mathbf{m}_R = (xz^2, xz, x, yz^2, yz, y, z^3, z^2, z, 1). Then for every row rr, the row rr of CC times mR\mathbf{m}_R equals brx(z) x+bry(z) y+br1(z)b^x_r(z)\,x + b^y_r(z)\,y + b^1_r(z), where brxb^x_r and bryb^y_r have degree at most 2 and br1b^1_r has degree at most 3.

Proof. M=[L∣R]M = [L \mid R] with LL invertible, and C=L−1RC = L^{-1}R. Multiplication by L−1L^{-1} is invertible, so Mm=0M\mathbf{m} = \mathbf{0} if and only if L−1Mm=[I∣C]m=0L^{-1}M\mathbf{m} = [I \mid C]\mathbf{m} = \mathbf{0}. The second statement is a regrouping of the ten terms by the factor xx, yy or 1. □\square

Lemma 4 (the hidden variable matrix). For r=0,1,2r = 0, 1, 2, let row rr of B(z)B(z) be the coefficients of xx, yy and 1 in (row 4+2r4 + 2r) minus zz times (row 5+2r5 + 2r) of [I∣C]m[I \mid C]\mathbf{m}, counting rows from 0. Then the left monomials cancel, B(z)B(z) has entries of degree at most 3, 3 and 4 in its three columns, and every solution (x,y,z)(x, y, z) of [I∣C]m=0[I \mid C]\mathbf{m} = \mathbf{0} satisfies B(z)(x,y,1)T=0B(z)(x, y, 1)^{\mathsf T} = \mathbf{0} and det⁡B(z)=0\det B(z) = 0. The determinant has degree at most 10.

Proof. In the order of the page, the left monomials of rows 4 to 9 are x2zx^2z, x2x^2, y2zy^2z, y2y^2, xyzxyz and xyxy. So row 4+2r4 + 2r is μz+(…)\mu z + (\ldots) and row 5+2r5 + 2r is μ+(…)\mu + (\ldots) with the same monomial μ∈{x2,y2,xy}\mu \in \{x^2, y^2, xy\}, and the difference removes μz\mu z. What remains is (b4+2rx−z b5+2rx) x+(b4+2ry−z b5+2ry) y+(b4+2r1−z b5+2r1)(b^x_{4+2r} - z\,b^x_{5+2r})\,x + (b^y_{4+2r} - z\,b^y_{5+2r})\,y + (b^1_{4+2r} - z\,b^1_{5+2r}), with degrees at most 3, 3 and 4 by Lemma 3. A solution makes every row of [I∣C]m[I \mid C]\mathbf{m} zero, so each difference is zero, which is B(z)(x,y,1)T=0B(z)(x, y, 1)^{\mathsf T} = \mathbf{0}. The vector (x,y,1)T(x, y, 1)^{\mathsf T} is not zero, so B(z)B(z) is singular. Each term of the determinant is a product of one entry from each column, of degree at most 3+3+4=103 + 3 + 4 = 10. □\square

Lemma 5 (the null vector). If a real 3×33 \times 3 matrix BB has rank 2, its null space is spanned by the cross product of any two of its rows that are linearly independent, and the largest of the three cross products of line L8 is such a product.

Proof. The cross product of two independent rows is nonzero and orthogonal to both. The third row is a combination of these two, so the product is orthogonal to all rows and lies in the null space, which has dimension 1. If two rows are dependent, their cross product is 0\mathbf{0}. Since the rank is 2, at least one pair is independent, so the largest product is nonzero and comes from an independent pair. □\square

Proof of part (a). Scale EE so that it is xX+yY+zZ+WxX + yY + zZ + W. By Lemma 2 and Lemma 3, (x,y,z)(x, y, z) solves [I∣C]m=0[I \mid C]\mathbf{m} = \mathbf{0}, and by Lemma 4, zz is a real root of det⁡B(z)\det B(z). Line L7 finds it. By (H4) and Lemma 5, the vector v\mathbf{v} of line L8 spans the null space of B(z)B(z), which contains (x,y,1)T(x, y, 1)^{\mathsf T}. So v=κ(x,y,1)T\mathbf{v} = \kappa(x, y, 1)^{\mathsf T} with κ≠0\kappa \ne 0, its third entry is not zero, and v1/v3=xv_1/v_3 = x and v2/v3=yv_2/v_3 = y. At an exact solution the residual of line L9 is zero, so the Gauss-Newton step is zero (or the solve fails), the residual cannot decrease, and line L9 returns (x,y,z)(x, y, z) unchanged. Line L10 adds the canonical form of EE. □\square

Proof of part (b). Every output is a canonical form of xX+yY+zZ+WxX + yY + zZ + W for real numbers xx, yy and zz, which satisfies the constraints by Lemma 1. □\square

Proof of part (c). By (H3) and Lemma 4, det⁡B(z)\det B(z) is a nonzero polynomial of degree at most 10, so it has at most 10 real roots. Line L8 gives at most one output per root. □\square

Proof of part (d). Let the 10 complex solutions have distinct values z1,…,z10z_1, \ldots, z_{10}. Each zkz_k is a root of det⁡B\det B by Lemma 4, which holds over the complex numbers with the same proof. A nonzero polynomial of degree at most 10 with 10 distinct roots has degree exactly 10 and no other roots. So each real root zz of det⁡B\det B is the zz of a complex solution (x,y,z)(x, y, z). By (H4), the null space of the real matrix B(z)B(z) is a real line, so xx and yy are real, and line L8 returns them. Then E(x,y,z)E(x, y, z) is a real matrix with Mm=0M\mathbf{m} = \mathbf{0}, and by the characterization theorem it is essential. The non-real roots of a real polynomial come in conjugate pairs, and the roots are simple, so the number of real roots of a polynomial of degree 10 is even. ■\blacksquare

Remark (more than five points). For n>5n > 5, line L2 takes the four right singular vectors of the four smallest singular values. They span the four-dimensional space of least algebraic error, and the rest of the algorithm is unchanged. On exact data from one essential matrix E0E_0 in general position, AA has rank 8, E0E_0 lies in the null space and therefore in the span, and part (a) still applies. On noisy data the outputs are essential matrices close to the space, not least squares solutions.

Remark (the polish and the tolerances). Line L9 is an addition of the code on this page. It takes Gauss-Newton steps on the ten cubics and keeps a step only if it lowers the norm of the residual, so in floating point it can only improve how well an output satisfies the cubics. It matters when two roots of det⁡B\det B are close, because then each root has few correct digits. The code skips a root when ∣v3∣≤10−12∥v∥|v_3| \le 10^{-12}\|\mathbf{v}\|; this is the case w=0w = 0 of the claim, or a failure of (H4). The roots come from the helper polyroots_real, which keeps the roots whose imaginary part is below its tolerance. Near a double root the count can then differ from the exact count.

Complexity

For five points the work is fixed: one SVD of a 5×95 \times 9 matrix (padded to 9×99 \times 9), the 10×2010 \times 20 matrix MM, one Gauss-Jordan elimination of a 10×1010 \times 10 system with 10 right sides, the determinant of a 3×33 \times 3 matrix of polynomials, and the real roots of a polynomial of degree 10. So the time is Θ(1)\Theta(1). For n>5n > 5 points, building AA and its SVD cost Θ(n)\Theta(n), and the rest is the same, so the time and the extra space are Θ(n)\Theta(n). Nister finds the real roots with Sturm sequences and bisection; a companion matrix eigenvalue method or another root finder also works.

In floating point the weak point is the roots of det⁡B(z)\det B(z): close roots lose about half of their digits, as the example shows. A short Newton or Gauss-Newton polish on the original ten equations, as in line L9, removes the loss.

Properties

  • Minimal. Five matches is the fewest for calibrated cameras.
  • At most 10 solutions. The polynomial has degree at most 10, and examples exist where all 10 roots are real. In practice the count of real solutions is small, often 2 to 4.
  • Even count. If the 10 complex solutions have different values of zz, the complex ones come in conjugate pairs, so the number of real solutions is even.
  • Works on planar scenes. Unlike the seven-point and eight-point algorithms, it still finds the true EE when all points lie on one plane.
  • Exact constraints. Every output is an exact essential matrix up to rounding; no rank step is needed.
  • Up to the twisted pair. EE fixes the pose only up to four choices; cheirality decides among them.

Variants and improvements

  • Gröbner basis form. Stewenius, Engels and Nister (2006) solve the same ten equations by a Gröbner basis and the eigenvalues of a 10×1010 \times 10 action matrix. It avoids the polynomial in one variable and is often more stable.
  • Automatic generators. Kukelova, Bujnak and Pajdla (2008) build such solvers automatically for many minimal problems.
  • More than five points. Using the four smallest singular vectors of an n×9n \times 9 matrix, as this implementation allows, gives a quick estimate for n>5n > 5, but a least squares fit on all inliers is better.
  • Seven or eight points. For uncalibrated cameras the seven-point algorithm finds FF.
  • Known rotation axis or planar motion. With extra knowledge, such as the vertical direction from an IMU, fewer points are needed, and the solvers are simpler.

When to use it

Use the five-point algorithm when the cameras are calibrated and the matches contain outliers. Inside RANSAC it needs 146 samples for an inlier ratio of 0.5 and 99% confidence, against 588 for the seven-point algorithm and 1177 for the eight-point algorithm, as the iteration bound gives. It is the core of Nister's visual odometry and of the initial pair in incremental structure from motion. After RANSAC, refine the pose on all inliers with a geometric cost.

Pitfalls

  • Pixel coordinates. The input must be normalized image coordinates K−1xK^{-1}\mathbf{x}, not pixels.
  • Only one solution kept. All real solutions are candidates. Score each of them against the other matches.
  • Close roots. Two roots of det⁡B(z)\det B(z) that are close lose digits. Polish the result, or use a more stable formulation.
  • Missed solutions. Fixing the weight of WW to 1 misses a solution with weight 0. This happens only on a set of data of measure zero, but data near it give large xx, yy, zz.
  • Sign and twist. EE and −E-E are the same, and each EE gives four poses. Use cheirality to pick one.
  • Pure rotation. If the translation is zero, E=0E = 0 and the problem has no meaning. Detect this case, for example with a rotation-only model, before the five-point solver.

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()
five_point_algorithm.py 226 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/five-point-algorithm/. The authors are listed in prov/SJPGET.jsonl.
"""Nister's five-point algorithm for the essential matrix.

Given 5 point pairs x1[i] <-> x2[i] in normalized image coordinates
(x = K^-1 (u, v, 1), given here by their first 2 entries), find every
essential matrix E with x2[i]^T E x1[i] = 0. The 5 linear equations leave a
4-dimensional space E = x X + y Y + z Z + W. The 10 cubic constraints
det E = 0 and 2 E E^T E - tr(E E^T) E = 0 are reduced by Gauss-Jordan
elimination to a 3 x 3 matrix B(z) of polynomials in z, with
B(z) (x, y, 1)^T = 0, and det B(z) is a polynomial of degree 10. Each real
root z gives one solution. A few Gauss-Newton steps on the 10 cubic
equations then polish (x, y, z); this step is an addition of this code, and
it restores the digits that a root of det B(z) loses when another root is near.

The code also accepts n > 5 points: the four right singular vectors of the
smallest singular values then span the space of least algebraic error.

The scale w = 1 of W is a choice: a solution with w = 0 is missed. This is
a set of measure zero. Every output has Frobenius norm 1, and its entry of
largest absolute value is positive. Cost: O(1) for 5 points (a 10 x 20
elimination and the roots of a polynomial of degree 10), O(n) for n points.
"""

from __future__ import annotations

from typing import Dict, List, Sequence, Tuple

from cvla import cross, norm, polyroots_real, scale, solve, svd

Matrix = List[List[float]]
Poly = Dict[Tuple[int, int, int], float]

# The 20 monomials x^a y^b z^c of degree <= 3, in the order of Nister (2004).
MONOMIALS = [(3, 0, 0), (0, 3, 0), (2, 1, 0), (1, 2, 0), (2, 0, 1), (2, 0, 0),
             (0, 2, 1), (0, 2, 0), (1, 1, 1), (1, 1, 0),
             (1, 0, 2), (1, 0, 1), (1, 0, 0), (0, 1, 2), (0, 1, 1), (0, 1, 0),
             (0, 0, 3), (0, 0, 2), (0, 0, 1), (0, 0, 0)]


def canonical(E: Sequence[Sequence[float]]) -> Matrix:
    """E 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(E)
    if f == 0.0:
        raise ValueError("zero matrix")
    big = max((x for row in E for x in row), key=abs)
    return scale(E, (1.0 if big > 0 else -1.0) / f)


# ------------------------------------------ polynomials in x, y and z

def _padd(p: Poly, q: Poly, c: float = 1.0) -> Poly:
    out = dict(p)
    for k, v in q.items():
        out[k] = out.get(k, 0.0) + c * v
    return out


def _pmul(p: Poly, q: Poly) -> Poly:
    out: Poly = {}
    for (a, b, c), u in p.items():
        for (d, e, f), v in q.items():
            k = (a + d, b + e, c + f)
            out[k] = out.get(k, 0.0) + u * v
    return out


def _pmatmul(A, B):
    return [[_padd(_padd(_pmul(A[i][0], B[0][j]), _pmul(A[i][1], B[1][j])), _pmul(A[i][2], B[2][j]))
             for j in range(3)] for i in range(3)]


def constraint_matrix(X: Matrix, Y: Matrix, Z: Matrix, W: Matrix) -> Matrix:
    """The 10 x 20 matrix of the cubic constraints on E = x X + y Y + z Z + W,
    in the monomial order MONOMIALS: row 0 is det E, rows 1 to 9 are the
    entries of 2 E E^T E - tr(E E^T) E."""
    E = [[{(1, 0, 0): X[i][j], (0, 1, 0): Y[i][j], (0, 0, 1): Z[i][j], (0, 0, 0): W[i][j]}
          for j in range(3)] for i in range(3)]
    Et = [[E[j][i] for j in range(3)] for i in range(3)]
    EEt = _pmatmul(E, Et)
    tr = _padd(_padd(EEt[0][0], EEt[1][1]), EEt[2][2])
    EEtE = _pmatmul(EEt, E)
    rows: List[Poly] = []
    d = _padd(_padd(_pmul(E[0][0], _padd(_pmul(E[1][1], E[2][2]), _pmul(E[1][2], E[2][1]), -1.0)),
                    _pmul(E[0][1], _padd(_pmul(E[1][2], E[2][0]), _pmul(E[1][0], E[2][2]), -1.0))),
              _pmul(E[0][2], _padd(_pmul(E[1][0], E[2][1]), _pmul(E[1][1], E[2][0]), -1.0)))
    rows.append(d)
    for i in range(3):
        for j in range(3):
            rows.append(_padd({k: 2.0 * v for k, v in EEtE[i][j].items()}, _pmul(tr, E[i][j]), -1.0))
    return [[r.get(m, 0.0) for m in MONOMIALS] for r in rows]


# ------------------------------------------- polynomials in z only

def _zadd(p: List[float], q: List[float], c: float = 1.0) -> List[float]:
    """p + c q, coefficients from the constant term up."""
    n = max(len(p), len(q))
    return [(p[i] if i < len(p) else 0.0) + c * (q[i] if i < len(q) else 0.0) for i in range(n)]


def _zmul(p: List[float], q: List[float]) -> List[float]:
    out = [0.0] * (len(p) + len(q) - 1)
    for i, a in enumerate(p):
        for j, b in enumerate(q):
            out[i + j] += a * b
    return out


def _zeval(p: List[float], z: float) -> float:
    s = 0.0
    for c in reversed(p):
        s = s * z + c
    return s


def _row_polys(c: List[float]) -> List[List[float]]:
    """The x, y and 1 parts of a reduced row, as polynomials in z (constant
    term first). c holds the 10 coefficients of xz^2, xz, x, yz^2, yz, y,
    z^3, z^2, z, 1."""
    return [[c[2], c[1], c[0]], [c[5], c[4], c[3]], [c[9], c[8], c[7], c[6]]]


def hidden_variable_matrix(C: Matrix) -> List[List[List[float]]]:
    """B(z) from the reduced rows: row r of B is row (4 + 2r) minus z times
    row (5 + 2r) of [I | C] (0-based), which removes x^2 z, y^2 z and x y z."""
    B = []
    for r in range(3):
        top, bottom = _row_polys(C[4 + 2 * r]), _row_polys(C[5 + 2 * r])
        B.append([_zadd(top[k], [0.0] + bottom[k], -1.0) for k in range(3)])
    return B


def _det3(B):
    def minor(a, b, c, d):
        return _zadd(_zmul(a, d), _zmul(b, c), -1.0)
    t0 = _zmul(B[0][0], minor(B[1][1], B[1][2], B[2][1], B[2][2]))
    t1 = _zmul(B[0][1], minor(B[1][0], B[1][2], B[2][0], B[2][2]))
    t2 = _zmul(B[0][2], minor(B[1][0], B[1][1], B[2][0], B[2][1]))
    return _zadd(_zadd(t0, t1, -1.0), t2)


def _monomials(x: float, y: float, z: float) -> List[float]:
    return [x ** a * y ** b * z ** c for a, b, c in MONOMIALS]


def _residual(M: Matrix, x: float, y: float, z: float) -> List[float]:
    m = _monomials(x, y, z)
    return [sum(p * q for p, q in zip(row, m)) for row in M]


def polish(M: Matrix, x: float, y: float, z: float, steps: int = 4) -> Tuple[float, float, float]:
    """Gauss-Newton steps on the 10 cubic equations M m(x, y, z) = 0. A step
    is kept only if it lowers the norm of the residual. A root of det B(z)
    that is close to another root has few correct digits; this restores
    them, because the solutions are far apart in (x, y, z)."""
    r = _residual(M, x, y, z)
    for _ in range(steps):
        cols = []
        for k in range(3):
            d = []
            for e in MONOMIALS:
                if e[k] == 0:
                    d.append(0.0)
                    continue
                f = list(e)
                f[k] -= 1
                d.append(e[k] * x ** f[0] * y ** f[1] * z ** f[2])
            cols.append([sum(p * q for p, q in zip(row, d)) for row in M])
        jtj = [[sum(a * b for a, b in zip(cols[i], cols[j])) for j in range(3)] for i in range(3)]
        jtr = [-sum(a * b for a, b in zip(cols[i], r)) for i in range(3)]
        try:
            step = solve(jtj, jtr)
        except ValueError:
            break
        nx, ny, nz = x + step[0], y + step[1], z + step[2]
        nr = _residual(M, nx, ny, nz)
        if norm(nr) >= norm(r):
            break
        x, y, z, r = nx, ny, nz, nr
    return x, y, z


# ------------------------------------------------------- the solver

def null_space_basis(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]]) -> List[Matrix]:
    """X, Y, Z, W: the right singular vectors of the 4 smallest singular
    values of the n x 9 matrix of the epipolar constraints."""
    a = []
    for p, q in zip(x1, x2):  # @line L1
        y1, y2 = [float(p[0]), float(p[1]), 1.0], [float(q[0]), float(q[1]), 1.0]
        a.append([u * w for u in y2 for w in y1])  # @line L1
    a += [[0.0] * 9 for _ in range(9 - len(a))]
    _, _, v = svd(a)
    basis = []
    for col in range(5, 9):  # @line L2
        f = [v[i][col] for i in range(9)]
        basis.append([f[0:3], f[3:6], f[6:9]])
    return basis


def five_point(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]]) -> List[Matrix]:
    """All essential matrices for n >= 5 pairs of normalized points, in
    canonical form. There are at most 10 solutions; often 2 to 4 are real."""
    if len(x1) != len(x2) or len(x1) < 5:
        raise ValueError("need at least 5 point pairs")
    X, Y, Z, W = null_space_basis(x1, x2)  # @line L2
    M = constraint_matrix(X, Y, Z, W)  # @line L3
    left = [row[:10] for row in M]  # @line L4
    right = [row[10:] for row in M]  # @line L4
    C = solve(left, right)  # @line L5
    B = hidden_variable_matrix(C)  # @line L6
    coeffs = _det3(B)  # @line L7
    out = []
    for z in polyroots_real(list(reversed(coeffs))):  # @line L7
        Bz = [[_zeval(p, z) for p in row] for row in B]
        cands = [cross(Bz[0], Bz[1]), cross(Bz[0], Bz[2]), cross(Bz[1], Bz[2])]
        v = max(cands, key=norm)  # @line L8
        if abs(v[2]) <= 1e-12 * norm(v):
            continue
        x, y = v[0] / v[2], v[1] / v[2]  # @line L8
        x, y, z = polish(M, x, y, z)  # @line L9
        E = [[x * X[i][j] + y * Y[i][j] + z * Z[i][j] + W[i][j] for j in range(3)] for i in range(3)]
        out.append(canonical(E))  # @line L10
    return out  # @line L11
test_five_point_algorithm.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/five-point-algorithm/. The authors are listed in prov/SJPGET.jsonl.
"""Tests of the five-point algorithm."""

import math
import random

import pytest

from cvla import det, matvec, mul, norm, skew, sub, svd, transpose
from five_point_algorithm import (MONOMIALS, canonical, constraint_matrix,
                                  five_point)

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."""
    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 scene(rng, n, R, t, planar=False):
    """n pairs of normalized points of 3D points in front of both cameras."""
    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.4 * x - 0.3 * 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([X1[0] / X1[2], X1[1] / X1[2]])
            x2.append([X2[0] / X2[2], X2[1] / X2[2]])
    return x1, x2


def random_pose(rng):
    R = rotation([rng.uniform(-1, 1) for _ in range(3)], rng.uniform(0.05, 0.5))
    t = [rng.uniform(-1, 1), rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)]
    return R, t


def check_solutions(sols, x1, x2, E_true):
    assert len(sols) % 2 == 0 and len(sols) <= 10
    assert any(norm(sub(E, canonical(E_true))) <= 1e-8 for E in sols)
    for E in sols:
        assert abs(norm(E) - 1.0) <= 1e-12
        for p, q in zip(x1, x2):
            r = matvec(E, [p[0], p[1], 1.0])
            assert abs(r[0] * q[0] + r[1] * q[1] + r[2]) <= 1e-9
        s = svd(E)[1]
        assert abs(s[0] - s[1]) <= 1e-8 and s[2] <= 1e-8


def test_constraint_matrix_against_direct_evaluation():
    rng = random.Random(1)
    X, Y, Z, W = ([[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)] for _ in range(4))
    M = constraint_matrix(X, Y, Z, W)
    for _ in range(3):
        x, y, z = rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2)
        mono = [x ** a * y ** b * z ** c for a, b, c in MONOMIALS]
        values = [sum(m * v for m, v in zip(row, mono)) for row in M]
        E = [[x * X[i][j] + y * Y[i][j] + z * Z[i][j] + W[i][j] for j in range(3)] for i in range(3)]
        EEt = mul(E, transpose(E))
        tr = EEt[0][0] + EEt[1][1] + EEt[2][2]
        T = mul(EEt, E)
        direct = [det(E)] + [2.0 * T[i][j] - tr * E[i][j] for i in range(3) for j in range(3)]
        assert max(abs(a - b) for a, b in zip(values, direct)) <= 1e-10


def test_worked_example():
    # The five points of the page, R about the Y axis and t = (1, 0, 0).
    x1, x2 = [], []
    for X1 in ([0, 0, 5], [1, 1, 4], [-1, 2, 6], [2, -1, 5], [-2, -2, 8]):
        X2 = [a + b for a, b in zip(matvec(R_EX, X1), T_EX)]
        x1.append([X1[0] / X1[2], X1[1] / X1[2]])
        x2.append([X2[0] / X2[2], X2[1] / X2[2]])
    assert max(abs(a - b) for a, b in zip(x2[1], [21 / 13, 5 / 13])) <= 1e-15
    sols = five_point(x1, x2)
    assert len(sols) == 4
    check_solutions(sols, x1, x2, [[0.0, 0.0, 0.0], [0.6, 0.0, -0.8], [0.0, 1.0, 0.0]])


def test_random_example_scene():
    rng = random.Random(2)
    x1, x2 = scene(rng, 5, R_EX, T_EX)
    check_solutions(five_point(x1, x2), x1, x2, [[0.0, 0.0, 0.0], [0.6, 0.0, -0.8], [0.0, 1.0, 0.0]])


@pytest.mark.parametrize("seed", range(3, 9))
def test_random_scenes(seed):
    rng = random.Random(seed)
    R, t = random_pose(rng)
    x1, x2 = scene(rng, 5, R, t)
    check_solutions(five_point(x1, x2), x1, x2, mul(skew(t), R))


def test_planar_scene_still_contains_the_truth():
    rng = random.Random(11)
    R, t = random_pose(rng)
    x1, x2 = scene(rng, 5, R, t, planar=True)
    check_solutions(five_point(x1, x2), x1, x2, mul(skew(t), R))


def test_more_than_five_points():
    rng = random.Random(12)
    R, t = random_pose(rng)
    x1, x2 = scene(rng, 9, R, t)
    sols = five_point(x1, x2)
    assert any(norm(sub(E, canonical(mul(skew(t), R)))) <= 1e-6 for E in sols)


def test_solution_counts_are_even_and_vary():
    counts = set()
    for seed in range(20, 30):
        rng = random.Random(seed)
        R, t = random_pose(rng)
        x1, x2 = scene(rng, 5, R, t)
        n = len(five_point(x1, x2))
        assert n % 2 == 0 and 2 <= n <= 10
        counts.add(n)
    assert len(counts) >= 2


def test_rejects_bad_input():
    with pytest.raises(ValueError):
        five_point([[0.0, 0.0]] * 4, [[0.0, 0.0]] * 4)
    with pytest.raises(ValueError):
        five_point([[0.0, 0.0]] * 5, [[0.0, 0.0]] * 6)

History

Kruppa (1913) studied the motion problem for five points and stated that it has at most 11 solutions. Demazure (1988) showed that the correct number of complex solutions is 10, and Faugeras and Maybank (1990) studied the same count. Nister (2003, journal version 2004) gave an efficient method: Gauss-Jordan elimination of the ten cubic constraints, a hidden variable matrix B(z)B(z), and a polynomial of degree 10 solved by Sturm sequences. It made the five-point algorithm practical inside RANSAC and for real-time visual odometry. Stewenius, Engels and Nister (2006) gave a Gröbner basis version.

References

  1. David Nister, An efficient solution to the five-point relative pose problem, IEEE Transactions on Pattern Analysis and Machine Intelligence 26(6), 2004, the four-dimensional null space, the ten cubic constraints, the Gauss-Jordan elimination of the 10 by 20 matrix and the polynomial of degree 10
  2. Olivier D. Faugeras and Stephen Maybank, Motion from point matches, multiplicity of solutions, International Journal of Computer Vision 4(3), 1990, 225-246, the number of solutions of the motion problem from five point matches
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 11.3, Two-frame structure from motion (the five-point algorithm for calibrated cameras)

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