Algorithm Search⌘K

Algorithmcore

Normalized eight-point algorithm

Also called Hartley's eight-point algorithm.

The eight-point algorithm run on Hartley-normalized points and mapped back by F = T2^T G T1. The normalization makes the linear system well conditioned and the result stable.

Time
Θ(n) worst · average · best
Space
Θ(n) extra
Where
n = the number of point pairs
Properties
deterministicexactofflineiterative
Origin
Richard Hartley, 1997

The normalized eight-point algorithm estimates the fundamental matrix from n≥8n \ge 8 point matches in pixels. It first gives each image its own similarity T1T_1 or T2T_2 that moves the centroid of its points to the origin and makes their mean distance to it 2\sqrt2, which is Hartley normalization. Then it runs the eight-point algorithm on the moved points, forces rank 2 there, and maps the result back by F=T2TGT1F = T_2^{\mathsf T}GT_1. Hartley (1997) showed that this cheap change turns a method thought to be useless on real images into a good one. It is the standard linear estimate of FF and the usual start of a geometric refinement.

In plain words

Pixel coordinates are numbers of a few hundred, and the equations of the eight-point algorithm multiply them together, so the table of equations mixes numbers near 1 with numbers near a hundred thousand. In such a table small errors in the big numbers hide the information in the small ones. The fix is to change units in each image before solving. Move the points so that they sit around the origin, and shrink them so that a typical point is about one unit away. Solve in these units, make the answer have the right form, and then convert it back to pixels. The extra work is tiny, and the answer becomes much more accurate.

The problem

Input. Point pairs (x1,i,x2,i)(\mathbf{x}_{1,i}, \mathbf{x}_{2,i}), i=1,…,ni = 1, \ldots, n, n≥8n \ge 8, as 2D pixel points (u,v)(u, v) that the algorithm extends to (u,v,1)T(u, v, 1)^{\mathsf T}. The points of each image must not all be equal.

Output. A 3×33 \times 3 matrix FF of rank 2 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 fundamental matrix in this form.

The algorithm

  1. NORMALIZED-EIGHT-POINT(x1_1 .. x1_n, x2_1 .. x2_n)
  2. 1T1 <- the similarity that moves the centroid of the x1_i to 0 and makes their mean distance to it sqrt(2)
  3. 2T2 <- the same similarity for the x2_i
  4. 3for i <- 1 to n
  5. 4y1 <- T1 x1_i ; y2 <- T2 x2_i
  6. 5append the row (y2[1] y1^T, y2[2] y1^T, y2[3] y1^T) to A
  7. 6g <- the right singular vector of A for its smallest singular value
  8. 7G <- the 3 x 3 matrix with rows g[1..3], g[4..6], g[7..9]
  9. 8(U, diag(s1, s2, s3), V) <- the SVD of G
  10. 9G <- U diag(s1, s2, 0) V^T
  11. 10F <- T2^T G T1
  12. 11return F / ||F||_F, with the sign that makes its entry of largest absolute value positive

Lines L1 and L2 compute each similarity from its own points: T=(s0−suˉ0s−svˉ001)T = \begin{pmatrix} s & 0 & -s\bar u \\ 0 & s & -s\bar v \\ 0 & 0 & 1 \end{pmatrix}, with (uˉ,vˉ)(\bar u, \bar v) the centroid and s=2/ds = \sqrt2/d for the mean distance dd to it. Lines L3 to L9 are the eight-point algorithm on the moved points: line L5 is the row with (Ag)i=y2TGy1(A\mathbf{g})_i = \mathbf{y}_2^{\mathsf T}G\mathbf{y}_1, line L6 minimizes ∥Ag∥\|A\mathbf{g}\| over unit vectors by the SVD, and line L9 forces rank 2. The rank step is done before line L10, so it acts on the well scaled matrix. Line L10 undoes the change: if y2TGy1=0\mathbf{y}_2^{\mathsf T}G\mathbf{y}_1 = 0 with y1=T1x1\mathbf{y}_1 = T_1\mathbf{x}_1 and y2=T2x2\mathbf{y}_2 = T_2\mathbf{x}_2, then x2T(T2TGT1)x1=0\mathbf{x}_2^{\mathsf T}(T_2^{\mathsf T}GT_1)\mathbf{x}_1 = 0. Since T1T_1 and T2T_2 are invertible, FF has rank 2 as GG has.

Example

Take the eight points of the eight-point example seen by two cameras with K=(50003200500240001)K = \begin{pmatrix} 500 & 0 & 320 \\ 0 & 500 & 240 \\ 0 & 0 & 1 \end{pmatrix}. The pixel points of image 1 are (320,240)(320, 240), (445,365)(445, 365), (236.67,406.67)(236.67, 406.67), (520,140)(520, 140), (195,115)(195, 115), (445,−10)(445, -10), (220,140)(220, 140) and (486.67,406.67)(486.67, 406.67); those of image 2 are (820,240)(820, 240), (1127.692,432.308)(1127.692, 432.308), (671.852,425.185)(671.852, 425.185), (1320,61.429)(1320, 61.429), (596.316,108.421)(596.316, 108.421), (1127.692,−144.615)(1127.692, -144.615), (667.826,131.304)(667.826, 131.304) and (1181.111,517.778)(1181.111, 517.778).

line value
L1 scale 0.00786050.0078605, translation (−2.81832,−1.77189)(-2.81832, -1.77189)
L2 scale 0.00436190.0043619, translation (−4.09608,−0.96606)(-4.09608, -0.96606)
L3 to L5 8 rows with entries of size about 1
L6 the singular values of AA are 5.515,4.766,4.321,3.260,2.215,0.863,0.154,0.08495.515, 4.766, 4.321, 3.260, 2.215, 0.863, 0.154, 0.0849 and 0; the ratio of the largest to the smallest nonzero one is 65.0
L7 to L9 GG has rank 2 already, so line L9 changes it only by rounding
L10, L11 F=(0002.7157×10−50−0.0267945−0.00651760.02263050.9993635)F = \begin{pmatrix} 0 & 0 & 0 \\ 2.7157 \times 10^{-5} & 0 & -0.0267945 \\ -0.0065176 & 0.0226305 & 0.9993635 \end{pmatrix}

The output is the canonical form of K−TEK−1∼(0000.60−592−14450022080)K^{-\mathsf T}EK^{-1} \sim \begin{pmatrix} 0 & 0 & 0 \\ 0.6 & 0 & -592 \\ -144 & 500 & 22080 \end{pmatrix}. The epipolar distances of the eight points are about 10−1310^{-13} pixels. Without lines L1 and L2, the nonzero singular values of AA run from 1.407×1061.407 \times 10^6 down to 1.1331.133, a ratio of 1.24×1061.24 \times 10^6. On these exact data both forms still give the true FF, but the difference shows with noise. In a test with 30 points, 10 random scenes and Gaussian noise of 1 pixel, the mean distance of the points to their epipolar lines was about 0.67 pixels for the normalized form and about 3.5 pixels for the plain form, and the normalized form was better in 8 of the 10 scenes.

Correctness

Line L10 is a change of coordinates: y2TGy1=x2TT2TGT1x1\mathbf{y}_2^{\mathsf T}G\mathbf{y}_1 = \mathbf{x}_2^{\mathsf T}T_2^{\mathsf T}GT_1\mathbf{x}_1. On exact data, the moved pairs are exact matches for the fundamental matrix T2−TF0T1−1T_2^{-\mathsf T}F_0T_1^{-1}, so the eight-point algorithm on them returns this matrix up to scale, and line L10 gives back F0F_0. The result has rank 2 because T1T_1 and T2T_2 are invertible. If the points of image 1 are moved by a similarity S1S_1 and those of image 2 by S2S_2, the normalized points change only by a rotation and a reflection, and the output becomes the canonical form of S2−TFS1−1S_2^{-\mathsf T}FS_1^{-1}. The full proof is below.

Proof: The normalized eight-point algorithm recovers F exactly from exact data, and its output moves with the data under similaritiesfull

We use the notation of the page. The input is 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} and xi′=(ui′,vi′,1)T\mathbf{x}'_i = (u'_i, v'_i, 1)^{\mathsf T}. 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. The canonical form of a nonzero matrix is the matrix divided by its Frobenius norm, times the sign of its entry of largest absolute value. ArawA_{\mathrm{raw}} is the matrix of the plain eight-point algorithm on the input points, and AA is the matrix of line L5, built from the moved points yi=Txi\mathbf{y}_i = T\mathbf{x}_i and yi′=T′xi′\mathbf{y}'_i = T'\mathbf{x}'_i.

Claim. (a) Let FF be a real matrix of rank 2 with xi′TFxi=0\mathbf{x}'^{\mathsf T}_i F\mathbf{x}_i = 0 for all ii, and let ArawA_{\mathrm{raw}} have rank 8. Then the algorithm returns the canonical form of FF. (b) On any input, the output has rank at most 2, and line L9 gives the matrix of rank at most 2 closest to GG in the Frobenius norm, in the normalized coordinates. (c) Let SS and S′S' be similarities of the two images, and move the input to SxiS\mathbf{x}_i and S′xi′S'\mathbf{x}'_i. If the smallest singular value of AA is simple and the third singular value of GG is simple, the output for the moved input is the canonical form of S′−TFoutS−1S'^{-\mathsf T} F_{\mathrm{out}} S^{-1}, where FoutF_{\mathrm{out}} is the output for the original input.

Lemma 1 (change of coordinates). Let TT and T′T' be invertible. A matrix GG satisfies yi′TGyi=0\mathbf{y}'^{\mathsf T}_i G\mathbf{y}_i = 0 for all ii if and only if F=T′TGTF = T'^{\mathsf T} G T satisfies xi′TFxi=0\mathbf{x}'^{\mathsf T}_i F\mathbf{x}_i = 0 for all ii. The map G↦T′TGTG \mapsto T'^{\mathsf T} G T is linear, one to one, and keeps the rank.

Proof. xi′TT′TGTxi=(T′xi′)TG(Txi)=yi′TGyi\mathbf{x}'^{\mathsf T}_i T'^{\mathsf T} G T\mathbf{x}_i = (T'\mathbf{x}'_i)^{\mathsf T} G (T\mathbf{x}_i) = \mathbf{y}'^{\mathsf T}_i G\mathbf{y}_i. The inverse map is F↦T′−TFT−1F \mapsto T'^{-\mathsf T} F T^{-1}, and multiplication by invertible matrices does not change the rank. □\square

By Lemma 1 of the eight-point proof, Arawf=0A_{\mathrm{raw}}\mathbf{f} = \mathbf{0} exactly when FF satisfies the constraints, and Ag=0A\mathbf{g} = \mathbf{0} exactly when GG does. So Lemma 1 here says that the linear map G↦T′TGTG \mapsto T'^{\mathsf T} G T sends the null space of AA onto the null space of ArawA_{\mathrm{raw}}, and the two null spaces have the same dimension. Both matrices have 9 columns, so AA has rank 8 exactly when ArawA_{\mathrm{raw}} has rank 8.

The similarities of lines L1 and L2 are invertible. Their last row is (0,0,1)(0, 0, 1), and their scale 2/d\sqrt2 / d is finite and positive, because the code stops when all points of one image coincide (d=0d = 0).

Proof of part (a). Put G0=T′−TFT−1G_0 = T'^{-\mathsf T} F T^{-1}. By Lemma 1, G0G_0 has rank 2 and satisfies the constraints on the moved points, so Ag0=0A\mathbf{g}_0 = \mathbf{0}. Since AA has rank 8, the null space of AA is the line spanned by g0\mathbf{g}_0. Line L6 returns a unit vector in it (Lemma 2 of the eight-point proof), so line L7 gives G=λG0G = \lambda G_0 with λ≠0\lambda \ne 0. This matrix has rank 2, so its third singular value is 0, and line L9 does not change it. Line L10 gives T′TλG0T=λFT'^{\mathsf T}\lambda G_0 T = \lambda F, and line L11 gives the canonical form of FF, for every λ≠0\lambda \ne 0. ■\blacksquare

Proof of part (b). Line L9 is Lemma 3 (i) of the eight-point proof, applied to GG. The output T′TGTT'^{\mathsf T} G T has the rank of GG by Lemma 1, so at most 2. □\square

Part (b) does not say that the output is the matrix of rank 2 closest to anything in the original coordinates. The rank step happens in the normalized frame, as Hartley (1997) does it.

Lemma 2 (the similarity part of the normalization). Let SS be a similarity of the plane, Sx=(sQp+c,1)S\mathbf{x} = (sQ\mathbf{p} + \mathbf{c}, 1) for x=(p,1)\mathbf{x} = (\mathbf{p}, 1), with s>0s > 0, QQ a 2×22 \times 2 orthogonal matrix and c∈R2\mathbf{c} \in \mathbb{R}^2. Let TT be the normalizing similarity of the points xi\mathbf{x}_i and T^\hat T that of the points SxiS\mathbf{x}_i. Then T^S=Q^T\hat T S = \hat Q T with Q^=(Q00T1)\hat Q = \begin{pmatrix} Q & \mathbf{0} \\ \mathbf{0}^{\mathsf T} & 1 \end{pmatrix}.

Proof. The centroid of the moved points is sQpˉ+csQ\bar{\mathbf{p}} + \mathbf{c}, where pˉ\bar{\mathbf{p}} is the old centroid, and each distance to it is multiplied by ss. So T^\hat T subtracts sQpˉ+csQ\bar{\mathbf{p}} + \mathbf{c} and scales by 2/(sd)\sqrt2/(s d). Then T^Sx=((2/d) Q(p−pˉ),1)=Q^Tx\hat T S\mathbf{x} = ((\sqrt2/d)\,Q(\mathbf{p} - \bar{\mathbf{p}}), 1) = \hat Q T\mathbf{x}. □\square

Proof of part (c). By Lemma 2, the moved points in the normalized frame are Q^yi\hat Q\mathbf{y}_i and Q^′yi′\hat Q'\mathbf{y}'_i, with Q^\hat Q and Q^′\hat Q' orthogonal. For a matrix GG put G^=Q^′GQ^T\hat G = \hat Q' G\hat Q^{\mathsf T}. Then (Q^′yi′)TG^(Q^yi)=yi′TGyi(\hat Q'\mathbf{y}'_i)^{\mathsf T}\hat G(\hat Q\mathbf{y}_i) = \mathbf{y}'^{\mathsf T}_i G\mathbf{y}_i and ∥G^∥F=∥G∥F\|\hat G\|_F = \|G\|_F. So the new matrix A^\hat A satisfies ∥A^g^∥=∥Ag∥\|\hat A\hat{\mathbf{g}}\| = \|A\mathbf{g}\| for all g\mathbf{g}, and the unit minimizer of line L6 moves from g\mathbf{g} to ±g^\pm\hat{\mathbf{g}} when the minimizer is unique up to sign. The SVD of G^\hat G is that of GG with UU and VV multiplied by Q^′\hat Q' and Q^\hat Q, so line L9 also commutes with G↦Q^′GQ^TG \mapsto \hat Q' G\hat Q^{\mathsf T} when the third singular value is simple. Line L10 for the moved input gives

T^′TQ^′GQ^TT^=(Q^′TT^′)TG(Q^TT^)=(T′S′−1)TG(TS−1)=S′−T(T′TGT)S−1,\hat T'^{\mathsf T}\hat Q' G\hat Q^{\mathsf T}\hat T = (\hat Q'^{\mathsf T}\hat T')^{\mathsf T} G (\hat Q^{\mathsf T}\hat T) = (T' S'^{-1})^{\mathsf T} G (T S^{-1}) = S'^{-\mathsf T}(T'^{\mathsf T} G T) S^{-1},

using Q^TT^=TS−1\hat Q^{\mathsf T}\hat T = T S^{-1} from Lemma 2. Up to the sign of g\mathbf{g}, this is S′−TFoutS−1S'^{-\mathsf T} F_{\mathrm{out}} S^{-1} before line L11, and line L11 removes the sign. ■\blacksquare

Remark (the plain algorithm is not covariant). Without lines L1 and L2, a translation of the pixel frame changes ArawA_{\mathrm{raw}} by a change of variables in f\mathbf{f} that is not orthogonal, so the minimizer of ∥Arawf∥\|A_{\mathrm{raw}}\mathbf{f}\| over unit vectors does not move with the data. The page shows a measured example of the effect on the accuracy. That the normalization improves the accuracy is a property of the condition number of AA (Hartley 1997); it is supported by analysis and by experiments, not by a theorem on the error of the output.

Complexity

Lines L1 and L2 cost Θ(n)\Theta(n), the loop costs Θ(n)\Theta(n), and the SVD of the n×9n \times 9 matrix AA costs Θ(n)\Theta(n) because the number of columns is fixed. Lines L7 to L11 work on 3×33 \times 3 matrices and cost Θ(1)\Theta(1). So the time is Θ(n)\Theta(n) and the extra space is Θ(n)\Theta(n) for AA, the same as the plain algorithm.

In floating point the gain is in the condition number of AA. After normalization each entry of a row is a product of two numbers of size about 1, so all nine columns of AA have about the same size. Hartley (1997) analyses the condition number of ATAA^{\mathsf T}A and shows how it grows with the size of the pixel coordinates when no normalization is done.

Properties

  • Exact on exact data. Like the plain algorithm, for eight or more exact matches in general position with two different camera centers.
  • Covariant under similarities. Moving the points of each image by a similarity changes the output in the same way as the true FF. The plain algorithm does not have this property.
  • Linear and non-iterative. The cost is about the same as the plain algorithm.
  • Algebraic, not geometric. The output minimizes the algebraic error of the normalized points. It is close to, but not equal to, the maximum likelihood estimate.
  • Rank step in normalized coordinates. The closest rank 2 matrix is taken for GG, not for FF. In pixel coordinates the Frobenius norm has no good meaning.

Variants and improvements

  • Anisotropic scaling. Scale uu and vv separately so that each has unit variance. This is a common alternative; the isotropic form of lines L1 and L2 is the usual choice.
  • Essential matrix. For calibrated cameras, run the essential variant on normalized image coordinates K−1xK^{-1}\mathbf{x}; those are already small and centered for most cameras, so the extra similarity matters less.
  • Seven points. The same normalization is used by the seven-point algorithm, which forces det⁡F=0\det F = 0 exactly.
  • Geometric refinement. Use the output to start a minimization of the Sampson distance or of the reprojection error. This is the Gold Standard method in Hartley and Zisserman.
  • Inside RANSAC. Use the seven-point algorithm as the minimal solver in RANSAC, and then the normalized eight-point algorithm on all inliers.

When to use it

Use it whenever a fundamental matrix must be found linearly from eight or more pixel matches: on the inliers of a robust fit, as the start of a nonlinear refinement, or alone when moderate accuracy is enough. There is no reason to run the plain algorithm on pixel data. For calibrated cameras and data with outliers, the five-point algorithm in RANSAC is usually the better first step.

Pitfalls

  • One similarity for both images. Each image needs its own TT from its own points.
  • The rank step after denormalizing. Forcing rank 2 on FF in pixels, instead of on GG, loses much of the gain.
  • Wrong side of the transpose. Line L10 is T2TGT1T_2^{\mathsf T}GT_1, not T2−1GT1T_2^{-1}GT_1; the fundamental matrix maps points to lines, so it changes by the transpose on the left.
  • All points equal. The mean distance is then 0 and the similarity is not defined. Check for this before line L1.
  • Degenerate scenes. Normalization does not fix planar scenes or pure rotations, where AA has rank at most 6.
  • Outliers. The least squares fit has no robustness. Use it inside or after RANSAC.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

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()
normalized_eight_point_algorithm.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/normalized-eight-point-algorithm/. The authors are listed in prov/6HV01C.jsonl.
"""Hartley's normalized eight-point algorithm for the fundamental matrix.

Given n >= 8 point pairs x1[i] <-> x2[i] (pixels, 2 entries each), find the
3 x 3 matrix F of rank 2 with x2[i]^T F x1[i] = 0, where the points are made
homogeneous by a third entry 1. Each image first gets its own similarity T1
or T2 that moves the centroid of its points to the origin and makes their
mean distance to it sqrt(2). The plain eight-point algorithm then runs on
the moved points, the rank 2 condition is forced there, and the result is
mapped back by F = T2^T F_hat T1.

The result has Frobenius norm 1, and its entry of largest absolute value is
positive. Cost: O(n) in total, because the SVD of the n x 9 matrix has a
fixed number of columns. With normalize=False the function is the plain
eight-point algorithm, kept here for comparison.
"""

from __future__ import annotations

import math
from typing import List, Sequence

from cvla import eye, matvec, mul, norm, nullvec, scale, svd, transpose

Matrix = List[List[float]]


def normalizing_similarity(pts: Sequence[Sequence[float]]) -> Matrix:
    """The 3 x 3 similarity T that moves the centroid of the points to the
    origin and scales them so that their mean distance to it is sqrt(2).

    Precondition: the points are not all equal. Cost O(n)."""
    n = len(pts)
    cx = sum(float(p[0]) for p in pts) / n
    cy = sum(float(p[1]) for p in pts) / n
    d = sum(math.hypot(float(p[0]) - cx, float(p[1]) - cy) for p in pts) / n
    if d == 0.0:
        raise ValueError("all points coincide")
    s = math.sqrt(2.0) / d
    return [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]]


def epipolar_row(y1: Sequence[float], y2: Sequence[float]) -> List[float]:
    """The row of A for one pair of homogeneous points: the Kronecker product
    of y2 and y1, so that row . f = y2^T F y1 for F stored row by row."""
    return [a * b for a in y2 for b in y1]


def canonical(F: Sequence[Sequence[float]]) -> Matrix:
    """F scaled to Frobenius norm 1, with its entry of largest absolute
    value positive (the first such entry, in row order, on a tie)."""
    f = norm(F)
    if f == 0.0:
        raise ValueError("zero matrix")
    big = max((x for row in F for x in row), key=abs)
    return scale(F, (1.0 if big > 0 else -1.0) / f)


def normalized_eight_point(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]],
                           normalize: bool = True) -> Matrix:
    """F from n >= 8 pairs of points (u, v), in canonical form."""
    n = len(x1)
    if n != len(x2):
        raise ValueError("x1 and x2 have different lengths")
    if n < 8:
        raise ValueError("need at least 8 point pairs")
    T1 = normalizing_similarity(x1) if normalize else eye(3)  # @line L1
    T2 = normalizing_similarity(x2) if normalize else eye(3)  # @line L2
    a = []
    for i in range(n):  # @line L3
        y1 = matvec(T1, [float(x1[i][0]), float(x1[i][1]), 1.0])  # @line L4
        y2 = matvec(T2, [float(x2[i][0]), float(x2[i][1]), 1.0])  # @line L4
        a.append(epipolar_row(y1, y2))  # @line L5
    f = nullvec(a)  # @line L6
    G = [f[0:3], f[3:6], f[6:9]]  # @line L7
    u, s, v = svd(G)  # @line L8
    G = mul(mul(u, [[s[0], 0.0, 0.0], [0.0, s[1], 0.0], [0.0, 0.0, 0.0]]), transpose(v))  # @line L9
    F = mul(mul(transpose(T2), G), T1)  # @line L10
    return canonical(F)  # @line L11


def epipolar_distances(F: Sequence[Sequence[float]], x1: Sequence[Sequence[float]],
                       x2: Sequence[Sequence[float]]) -> List[float]:
    """For each pair, the distance in pixels from x2 to the epipolar line
    F x1 in image 2."""
    out = []
    for p, q in zip(x1, x2):
        line = matvec(F, [p[0], p[1], 1.0])
        out.append(abs(line[0] * q[0] + line[1] * q[1] + line[2]) / math.hypot(line[0], line[1]))
    return out
test_normalized_eight_point_algorithm.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/normalized-eight-point-algorithm/. The authors are listed in prov/6HV01C.jsonl.
"""Tests of the normalized eight-point algorithm."""

import math
import random

import pytest

from cvla import inv, matvec, mul, norm, skew, sub, svd, transpose
from normalized_eight_point_algorithm import (canonical, epipolar_distances,
                                              epipolar_row,
                                              normalized_eight_point,
                                              normalizing_similarity)

K1 = [[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]
K2 = [[450.0, 0.0, 300.0], [0.0, 460.0, 250.0], [0.0, 0.0, 1.0]]


def rotation(axis, angle):
    """Rodrigues formula, written out."""
    a = [c / norm(axis) for c in axis]
    k = skew(a)
    k2 = mul(k, k)
    s, c = math.sin(angle), math.cos(angle)
    return [[(1.0 if i == j else 0.0) + s * k[i][j] + (1.0 - c) * k2[i][j]
             for j in range(3)] for i in range(3)]


def project(K, X):
    y = matvec(K, X)
    return [y[0] / y[2], y[1] / y[2]]


def two_views(rng, n):
    """A random relative pose and n pixel pairs of points in front of both
    cameras. Returns R, t, x1, x2."""
    R = rotation([rng.uniform(-1, 1) for _ in range(3)], rng.uniform(0.05, 0.3))
    t = [rng.uniform(-1, 1), rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3)]
    x1, x2 = [], []
    while len(x1) < n:
        X1 = [rng.uniform(-2.0, 2.0), rng.uniform(-2.0, 2.0), rng.uniform(4.0, 8.0)]
        X2 = [a + b for a, b in zip(matvec(R, X1), t)]
        if X2[2] > 0.5:
            x1.append(project(K1, X1))
            x2.append(project(K2, X2))
    return R, t, x1, x2


def true_F(R, t):
    return canonical(mul(mul(transpose(inv(K2)), mul(skew(t), R)), inv(K1)))


def noisy(rng, pts, sigma):
    return [[c + rng.gauss(0.0, sigma) for c in p] for p in pts]


def test_similarity_values():
    T = normalizing_similarity([[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]])
    s = math.sqrt(2.0) / math.sqrt(2.0)
    assert T == [[s, 0.0, -s], [0.0, s, -s], [0.0, 0.0, 1.0]]
    pts = [[3.0, 1.0], [7.0, 4.0], [-2.0, 5.0], [0.0, 0.0]]
    T = normalizing_similarity(pts)
    ys = [matvec(T, [p[0], p[1], 1.0]) for p in pts]
    assert abs(sum(y[0] for y in ys)) <= 1e-12 and abs(sum(y[1] for y in ys)) <= 1e-12
    assert abs(sum(math.hypot(y[0], y[1]) for y in ys) / 4 - math.sqrt(2.0)) <= 1e-12


@pytest.mark.parametrize("seed", [1, 2, 3])
def test_exact_recovery(seed):
    rng = random.Random(seed)
    R, t, x1, x2 = two_views(rng, 15)
    F = normalized_eight_point(x1, x2)
    assert norm(sub(F, true_F(R, t))) <= 1e-8
    s = svd(F)[1]
    assert s[2] <= 1e-12
    assert max(epipolar_distances(F, x1, x2)) <= 1e-8


def test_rectified_pair():
    # Pure translation along +X with equal K: F ~ [[0,0,0],[0,0,-1],[0,1,0]].
    rng = random.Random(4)
    x1, x2 = [], []
    for _ in range(10):
        X = [rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(4, 8)]
        x1.append(project(K1, X))
        x2.append(project(K1, [X[0] - 0.5, X[1], X[2]]))
    F = normalized_eight_point(x1, x2)
    r = 1.0 / math.sqrt(2.0)
    assert norm(sub(F, [[0.0, 0.0, 0.0], [0.0, 0.0, -r], [0.0, r, 0.0]])) <= 1e-8 or \
        norm(sub(F, [[0.0, 0.0, 0.0], [0.0, 0.0, r], [0.0, -r, 0.0]])) <= 1e-8


def test_covariant_under_similarities():
    # Moving each image by a similarity S gives S2^-T F S1^-1, even with noise.
    rng = random.Random(5)
    _, _, x1, x2 = two_views(rng, 20)
    x1, x2 = noisy(rng, x1, 1.0), noisy(rng, x2, 1.0)
    F = normalized_eight_point(x1, x2)

    def sim(angle, s, tx, ty):
        c, d = s * math.cos(angle), s * math.sin(angle)
        return [[c, -d, tx], [d, c, ty], [0.0, 0.0, 1.0]]

    S1, S2 = sim(0.7, 2.5, 100.0, -40.0), sim(-1.2, 0.3, -7.0, 900.0)
    m1 = [matvec(S1, [p[0], p[1], 1.0])[:2] for p in x1]
    m2 = [matvec(S2, [p[0], p[1], 1.0])[:2] for p in x2]
    G = normalized_eight_point(m1, m2)
    expected = canonical(mul(mul(transpose(inv(S2)), F), inv(S1)))
    assert norm(sub(G, expected)) <= 1e-8


def test_normalization_improves_conditioning():
    rng = random.Random(6)
    _, _, x1, x2 = two_views(rng, 30)
    plain = [epipolar_row([p[0], p[1], 1.0], [q[0], q[1], 1.0]) for p, q in zip(x1, x2)]
    T1, T2 = normalizing_similarity(x1), normalizing_similarity(x2)
    moved = [epipolar_row(matvec(T1, [p[0], p[1], 1.0]), matvec(T2, [q[0], q[1], 1.0]))
             for p, q in zip(x1, x2)]
    sp, sn = svd(plain)[1], svd(moved)[1]
    # ratio of the largest to the second smallest singular value
    assert sp[0] / sp[7] > 1e4
    assert sn[0] / sn[7] < 1e2


def test_more_accurate_than_plain_under_noise():
    # sigma = 1 pixel, 30 points, 10 scenes: mean distance in pixels of the
    # noise-free points to the estimated epipolar lines.
    rng = random.Random(10)
    dn, dp = 0.0, 0.0
    for _ in range(10):
        _, _, x1, x2 = two_views(rng, 30)
        n1, n2 = noisy(rng, x1, 1.0), noisy(rng, x2, 1.0)
        dn += sum(epipolar_distances(normalized_eight_point(n1, n2), x1, x2)) / 300.0
        dp += sum(epipolar_distances(normalized_eight_point(n1, n2, normalize=False), x1, x2)) / 300.0
    assert dn < 1.0
    assert dp > 2.0 * dn


def test_rejects_bad_input():
    with pytest.raises(ValueError):
        normalized_eight_point([[0.0, 0.0]] * 7, [[1.0, 1.0]] * 7)
    with pytest.raises(ValueError):
        normalized_eight_point([[0.0, 0.0]] * 8, [[1.0, 1.0]] * 8)

History

The eight-point algorithm of Longuet-Higgins (1981) was long held to be very sensitive to noise, and iterative methods were preferred. Hartley (1997), in a paper titled "In defense of the eight-point algorithm", showed that the poor results came from the bad condition of the linear system on pixel coordinates, and that translating and scaling the points first gives results close to those of iterative methods in his tests. The same idea applies to other linear estimates, such as the DLT for homographies. Hartley and Zisserman (2000, second edition 2004) present the normalized eight-point algorithm in Section 11.2.

References

  1. Richard I. Hartley, In defense of the eight-point algorithm, IEEE Transactions on Pattern Analysis and Machine Intelligence 19(6), 1997, 580-593, the isotropic normalization of the points, the condition of the linear system, and the comparison with iterative methods
  2. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 11.2, The normalized 8-point algorithm
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 11.3, Two-frame structure from motion (the normalized eight-point algorithm)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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