Algorithm Search⌘K

Algorithmadvanced

Nister visual odometry

Also called feature-based visual odometry.

Match corners between frames, find each new camera pose with a five-point or three-point solver inside preemptive RANSAC, and triangulate, for a single camera or a stereo rig.

Time
O(N (M B + M log M + k n + f n)) worst · averageO(N (M B + M log M + n)) best
Space
O(M + f n) extra
Where
B = the block size of the preemptive scoring; M = the number of hypotheses per frame; N = the number of frames; f = the firewall spacing in frames; k = the number of Gauss-Newton iterations; n = the number of tracks seen in a frame
Properties
randomizednot exactiterativeonline
Origin
David Nistér, Oleg Naroditsky, James Bergen, 2004

Nister visual odometry is the system of Nistér, Naroditsky and Bergen (CVPR 2004) that estimates the motion of a calibrated camera, frame by frame, from corner matches. It gave the name to the visual odometry problem. Each new pose comes from a minimal solver inside preemptive RANSAC: the five-point algorithm for the relative pose of a single camera at the start, and the three-point resection (P3P) against already triangulated points after that. A short Gauss-Newton refinement follows. New points are triangulated between the two most distant views that are allowed, and a "firewall" every few frames stops old frames from taking part in new triangulations, so an error does not pass forward for ever. With one camera the result has an unknown scale; with a calibrated stereo rig the same scheme gives metric motion.

In plain words

You walk with a camera and want to know your path. In each picture, find many small corners, and match them with the corners of the next picture. From a few matches you can guess how the camera moved. Some matches are wrong, so you make many guesses from random small sets of matches and keep the guess that most matches agree with. To save time, you test all guesses on a few matches first, drop the worse half, test the rest on more matches, and so on. From the matches and the motion you also find where the corners are in space. Later pictures then need only three known points per guess. With one camera you never learn the real size of the steps, only their ratios. With two cameras side by side you do.

The problem

The input is a sequence of NN frames of a calibrated camera and, for each frame kk, a set of tracks: a track id and a point x=(x,y)x = (x, y) in normalized image coordinates K−1(u,v,1)TK^{-1}(u, v, 1)^{\mathsf T}. Some points are wrong matches (outliers). A pose (Rk,tk)(R_k, t_k) maps a world point into camera kk as Xc=RkX+tkX_c = R_k X + t_k, and the world frame is the camera of frame 0. The output is one pose per frame. For one camera the poses are found up to one global scale, which the algorithm fixes by setting ∣t2∣=1|t_2| = 1. For a rectified stereo pair with known baseline bb, the poses are metric.

The corner detection and matching are part of the system but not of the code here. In the paper, Harris corners are found in every frame and matched between frames by normalized correlation of small patches; they are matched again in each frame and not tracked by a flow method, which keeps the feature positions from drifting. The code takes the tracks as input.

The algorithm

  1. NISTER-VO-MONO(tracks of frames 0 … N-1, firewall spacing f, threshold τ)
  2. 1pose[0] ← (I, 0)
  3. 2E ← preemptive RANSAC over five-point hypotheses on the tracks seen in frames 0 and 2
  4. 3(R, t) ← the decomposition of E that puts most inliers in front of both cameras; pose[2] ← (R, t / |t|)
  5. 4map ← linear triangulation of the inliers from frames 0 and 2; firewall ← 0
  6. 5for k in 1, 3, 4, …, N - 1 do
  7. 6(R, t) ← preemptive RANSAC over P3P hypotheses on the map points seen in frame k
  8. 7pose[k] ← Gauss-Newton refinement of (R, t) on the reprojection error of the inliers
  9. 8for each track seen in frame k do
  10. 9i ← the first frame ≥ firewall that sees the track
  11. 10if k - i ≥ 2 and the point from frames i and k is in front with error ≤ τ in both then map[track] ← that point
  12. 11if k mod f = 0 then firewall ← k
  13. 12return pose

Lines L2 and L6 use the preemptive scoring of preemptive RANSAC. The code draws MM minimal samples, keeps every solution of each sample as a hypothesis (up to 10 for five points, up to 4 for three points), puts the observations in random order and adds min⁡(e2,τ2)\min(e^2, \tau^2) to each live hypothesis for each observation. After each block of BB observations it keeps the better half. For the essential matrix, ee is the Sampson distance; for a pose, ee is the reprojection error in normalized coordinates, and a point behind the camera costs τ2\tau^2.

Line L3 is the decomposition of the essential matrix into four candidates (R,±t)(R, \pm t), with R=UWVTR = U W V^{\mathsf T} or UWTVTU W^{\mathsf T} V^{\mathsf T}; the candidate is chosen by a vote over the inliers on the cheirality test. Line L3 also fixes the scale of the whole run. Line L7 runs Gauss-Newton on ∑i∣π(RXi+t)−xi∣2\sum_i |\pi(R X_i + t) - x_i|^2 with the update R←exp⁡([ω]×)RR \leftarrow \exp([\omega]_\times) R, t←exp⁡([ω]×)t+δtt \leftarrow \exp([\omega]_\times) t + \delta t and keeps a step only if the cost goes down. Lines L8 to L10 triangulate with the linear method from the oldest view that the firewall allows, which is the widest baseline available. Line L11 moves the firewall; frames before it are no longer used to triangulate.

Stereo. For a rectified pair, the points are triangulated from the left and right images of frame k−1k - 1, P3P in preemptive RANSAC against the left image of frame kk gives the motion between the two frames, and the poses are chained. Nistér and his coauthors reported that this 3D-to-2D scheme works much better than the alignment of two 3D point sets triangulated at frames k−1k - 1 and kk, because the triangulated depths are uncertain.

Differences from the paper. The paper runs the five-point preemptive RANSAC over three consecutive frames at the start. The code makes the start from frames 0 and 2 and then places frame 1 by P3P.

Example

Firewall bookkeeping. Take f=4f = 4 and a track that is seen in every frame. At k=1k = 1 the first frame that sees it is 0, and 1−0<21 - 0 < 2, so nothing changes. At k=3k = 3 the point is triangulated again from frames 0 and 3. At k=4k = 4 it is triangulated from frames 0 and 4, and then the firewall moves to 4. At k=5k = 5 the first allowed frame is 4 and 5−4<25 - 4 < 2, so the point keeps the value from frames 0 and 4. At k=6k = 6 it is triangulated from frames 4 and 6. From now on frames 0 to 3 have no effect on the map.

A synthetic run. The test builds 8 frames of a camera with fx=fy=500f_x = f_y = 500 and a 640×480640 \times 480 image that moves forward by 0.350.35, right by 0.150.15 and down by 0.020.02 per frame and turns a little about all three axes. 60 points lie at depths 8 to 16 in front of all frames, and 10 percent of all observations are replaced by random points in the image. The camera of frame 2 is at distance 0.76260.7626 from frame 0, so the algorithm returns every translation multiplied by 1/0.7626=1.31131/0.7626 = 1.3113. After this one scale is removed, the largest rotation error is 3×10−153 \times 10^{-15} radians and the largest translation error is 6×10−146 \times 10^{-14}. The stereo version with a baseline of 0.50.5 and the same kind of outliers returns the metric poses exactly. With Gaussian noise of σ=0.5\sigma = 0.5 pixels and 50 points, the stereo run over 6 frames had rotation errors up to 0.230.23 degrees and position errors up to 0.050.05 on a path of length 1.91.9. That last result is one run on one synthetic scene, not a property of the method.

Correctness

The full proof is in proofs/correctness.md. It covers the case without noise and makes one assumption about the robust steps: the hypothesis chosen at lines L2 and L6 is one that was made from a sample of correct matches, and no wrong match falls within τ\tau of a consistent position. Under that assumption it shows that the algorithm returns the true poses multiplied by the single scale 1/∣t2∣1/|t_2|. The steps are: the true essential matrix is among the five-point solutions; exactly one of the four decompositions puts a point in front of both cameras; linear triangulation with exact poses returns the scaled point; the true pose is among the P3P solutions, by the derivation of Grunert's quartic; and Gauss-Newton stays at an exact pose because the gradient there is zero. RANSAC itself gives no guarantee: whether a good sample is drawn and survives the preemption is a matter of probability, with the bound of ransac-iteration-bound under its assumptions.

Proof: Without noise, and when the robust steps pick a hypothesis from correct matches, the monocular scheme returns the true poses up to one scalefull

Setting. The true poses are (Rk,tk)(R_k, t_k), with (R0,t0)=(I,0)(R_0, t_0) = (I, 0) and t2≠0t_2 \ne 0. Every correct observation is exact: x=π(RkX+tk)x = \pi(R_k X + t_k) with π(a,b,c)=(a/c,b/c)\pi(a, b, c) = (a/c, b/c) and RkX+tkR_k X + t_k in front of the camera. Let s=1/∣t2∣s = 1/|t_2|. The scaled scene has poses (Rk,stk)(R_k, s t_k) and points sXs X. It gives the same observations, because π(Rk(sX)+stk)=π(s(RkX+tk))=π(RkX+tk)\pi(R_k (sX) + s t_k) = \pi(s(R_k X + t_k)) = \pi(R_k X + t_k) for s>0s > 0. We show that every pose and every map point that the algorithm stores is the one of the scaled scene.

Assumptions. (A1) At lines L2 and L6 the hypothesis that preemptive scoring returns is a solution of a minimal sample of correct observations that equals the true model. (A2) No wrong observation is within τ\tau of the position that the true model gives, so the inlier sets and the checks of line L10 contain only correct observations. (A3) General position: the five and three points of the samples are not degenerate for their solvers, and no point lies on the line through two camera centers that are used to triangulate it. RANSAC does not guarantee (A1); it holds with a probability that grows with the number of samples, as described by ransac-iteration-bound.

Lemma 1 (line L2). The true essential matrix E=[t2]×R2E = [t_2]_\times R_2 satisfies x2TEx1=0x_2^{\mathsf T} E x_1 = 0 on every correct pair of frames 0 and 2, written as homogeneous 3-vectors, because x2∝R2x1λ+t2x_2 \propto R_2 x_1 \lambda + t_2 for the depth λ\lambda of the point in frame 0, and [t2]×[t_2]_\times kills t2t_2 and makes [t2]×R2x1[t_2]_\times R_2 x_1 orthogonal to R2x1R_2 x_1. The five-point method returns every real solution of the five linear equations and the ten cubic constraints that every essential matrix satisfies, and under (A3) the true EE, scaled to norm 1, is among them. By (A1) line L2 returns it, up to a nonzero factor.

Lemma 2 (line L3). Let E=Udiag⁡(σ,σ,0)VTE = U \operatorname{diag}(\sigma, \sigma, 0) V^{\mathsf T} with det⁡U=det⁡V=1\det U = \det V = 1. The rotations RR with [t]×R∝E[t]_\times R \propto E for a unit tt are exactly UWVTU W V^{\mathsf T} and UWTVTU W^{\mathsf T} V^{\mathsf T}, and t=±u3t = \pm u_3, the third column of UU (Hartley and Zisserman, second edition, Results 9.18 and 9.19). So the four candidates contain (R2,t2/∣t2∣)=(R2,st2)(R_2, t_2/|t_2|) = (R_2, s t_2). For a point XX in front of both true cameras, of the four candidates only the true one triangulates XX in front of both cameras: changing the sign of tt puts the point behind both cameras, and the other rotation (the "twisted pair") puts it behind exactly one of them (the same book, Section 9.6.3). By (A2), every inlier is a correct observation of a point in front of both cameras, so the true candidate gets every vote and each other candidate gets none, and line L3 selects (R2,st2)(R_2, s t_2).

Lemma 3 (lines L4 and L10). Let two poses (Ra,sta)(R_a, s t_a) and (Rb,stb)(R_b, s t_b) be correct for the scaled scene, and let xax_a, xbx_b be correct observations of XX. Then sXsX makes all four rows of the linear triangulation zero: xP3−P1x P^3 - P^1 applied to (sX,1)(sX, 1) is x c−ax \, c - a, where (a,b,c)(a, b, c) are the camera coordinates of sXsX, and x=a/cx = a/c. Under (A3) the four rows have rank 3, so the null vector is (sX,1)(sX, 1) up to a factor, and the returned point is sXsX. Its error is 0 and it is in front, so it passes the check. A point from a wrong observation is rejected by (A2). So every stored point is the scaled true point.

Lemma 4 (line L6, P3P). Let fif_i be the unit bearings of three correct observations in frame kk and XiX_i the stored points, which by Lemma 3 are scaled true points. The true distances di=∣RkXi+stk∣d_i = |R_k X_i + s t_k| satisfy the three law-of-cosines equations dj2+dl2−2djdlcos⁡θjl=∣Xj−Xl∣2d_j^2 + d_l^2 - 2 d_j d_l \cos\theta_{jl} = |X_j - X_l|^2. Write d2=ud1d_2 = u d_1 and d3=vd1d_3 = v d_1, and a2,b2,c2a^2, b^2, c^2 for the squared distances of the pairs (2, 3), (1, 3) and (1, 2). Then d12=b2/q(v)d_1^2 = b^2 / q(v) with q(v)=1+v2−2vcos⁡βq(v) = 1 + v^2 - 2 v \cos\beta, and the other two equations become

b2u2−2b2cos⁡γ u+b2−c2q(v)=0,b2u2−2b2cos⁡α vu+b2v2−a2q(v)=0.b^2 u^2 - 2 b^2 \cos\gamma\, u + b^2 - c^2 q(v) = 0, \qquad b^2 u^2 - 2 b^2 \cos\alpha\, v u + b^2 v^2 - a^2 q(v) = 0 .

Their difference is linear in uu and gives uD(v)=N(v)u D(v) = N(v) with D=2b2(cos⁡γ−vcos⁡α)D = 2 b^2 (\cos\gamma - v \cos\alpha) and N=b2−b2v2+(a2−c2)q(v)N = b^2 - b^2 v^2 + (a^2 - c^2) q(v). Multiplying the first equation by D2D^2 and putting uD=Nu D = N gives the quartic b2N2−2b2cos⁡γ ND+(b2−c2q)D2=0b^2 N^2 - 2 b^2 \cos\gamma\, N D + (b^2 - c^2 q) D^2 = 0. The true vv is a positive root of it, and under (A3) D(v)≠0D(v) \ne 0, so the code recovers the true uu, d1d_1, and the true camera points difid_i f_i. The code then fits (R,t)(R, t) to three pairs Xi↦difiX_i \mapsto d_i f_i by the SVD method with the sign correction that forces det⁡R=1\det R = 1. The three points are not collinear by (A3), so the rigid motion between them is unique and the SVD method returns it with zero residual. Hence the true (Rk,stk)(R_k, s t_k) is among the hypotheses, and by (A1) line L6 returns it.

Lemma 5 (line L7). At the true pose every residual of the inliers is 0, by (A2). The Gauss-Newton right-hand side −JTr-J^{\mathsf T} r is then 0, and the step is 0 (or the solve fails). The candidate cost equals the current cost 0, which is not smaller, so the loop stops and returns the true pose unchanged.

Induction. Before the loop, Lemmas 1 to 3 give pose 0, pose 2 and the map for the scaled scene. Assume that all poses and map points stored before frame kk are those of the scaled scene. Lemma 4 and Lemma 5 give pose kk, and Lemma 3 keeps the map correct after lines L8 to L10. Line L11 changes only which frames line L9 may use; every allowed frame already has a correct pose. So after the loop every pose is (Rk,stk)(R_k, s t_k). This is the true trajectory up to the single scale s=1/∣t2∣s = 1/|t_2|, which cannot be recovered from one camera because the scaled scene gives the same images. ■\blacksquare

Stereo. For the rectified rig, the right camera of frame k−1k - 1 has the known pose (I,(−b,0,0))(I, (-b, 0, 0)) relative to the left one. Lemma 3 with these two poses gives the true points in the left camera of frame k−1k - 1 with their metric size. Lemmas 4 and 5 give the true motion between frames k−1k - 1 and kk, and composing the motions gives the true metric poses.

What is not proved. With noise, the outputs are estimates; the errors add up along the path and the monocular scale drifts. Assumptions (A1) and (A2) are about luck and data, not about the algorithm; a test with a fixed seed shows that they hold for that seed.

Complexity

  • One hypothesis. The five-point solver eliminates a fixed 10×2010 \times 20 matrix and finds the roots of a degree 10 polynomial; P3P solves a quartic. Each costs O(1)O(1) in the real RAM, with constants of different sizes.
  • Preemptive scoring. With MM hypotheses and blocks of BB, the scorings are at most B(M+M/2+M/4+… )≤2BMB(M + M/2 + M/4 + \dots) \le 2BM, and the sorts cost O(Mlog⁡M)O(M \log M). Shuffling nn observations is O(n)O(n).
  • Refinement. One Gauss-Newton iteration on nn points builds a 6×66 \times 6 normal matrix in O(n)O(n) and solves it in O(1)O(1); kk iterations cost O(kn)O(kn). This is a cost per iteration, not a convergence bound.
  • Triangulation. Finding the first allowed frame of a track looks at no more than ff frames, and each triangulation is a fixed size SVD, so O(fn)O(fn) per frame.
  • Total. O(N(MB+Mlog⁡M+kn+fn))O(N(MB + M \log M + kn + fn)) time, and O(M+fn)O(M + fn) extra space for the hypotheses and the tracks behind the firewall. Time per frame does not grow with NN, which is what makes the method real time.

Properties

  • Online and bounded. Each frame costs the same, set in advance by MM and BB. This is the reason for the preemptive scoring.
  • Randomized. Results depend on the random samples. A fixed seed gives a fixed result.
  • Scale. With one camera the scale is set once at the start and then carried by the map. Errors in the map change it slowly over time; see scale drift. A stereo rig gives the scale in every frame.
  • Drift. Each pose is found from the previous map, so errors add up along the path. Without a global step such as loop closure, nothing removes them.
  • Matched, not tracked, corners. Detecting corners in each frame and matching them keeps each position tied to the image, which avoids the slow slide of positions that a frame-to-frame tracker can have.

Variants and improvements

  • Stereo scheme. As above, with metric scale and three-point resection against stereo points. The journal version (J. Field Robotics 2006) describes the system in more detail and reports runs on ground vehicles.
  • Local bundle adjustment. Later systems refine the last few poses and points together; see sliding window bundle adjustment. The tutorial of Scaramuzza and Fraundorfer cites a final position error 2 to 5 times smaller with it on a 10 km run by Konolige and others; that is a measured result.
  • Keyframes. Use only frames where the view has changed enough for the triangulation and the resection; see keyframe selection.
  • Other robust estimators. Replace preemptive scoring by plain RANSAC or MSAC when the time per frame need not be fixed.
  • Feature systems with a map. PTAM and ORB-SLAM keep keyframes and a map, run bundle adjustment and close loops.
  • Direct methods. Semi-direct visual odometry and direct sparse odometry use pixel intensities instead of matched corners.

When to use it

Use this scheme when you have a calibrated camera or stereo rig, an image with enough corners, and a need for a fixed time per frame. It is the base of most feature-based visual odometry. Use stereo when you need metric scale and the scene is not too far for the baseline. Prefer a direct method when the image has little corner texture but many edges or smooth gradients, and add bundle adjustment and loop closure when you need a consistent map over long paths.

Pitfalls

  • Small motion at the start. If the camera barely moves between frames 0 and 2, the essential matrix is poorly fixed and the triangulated depths are noise. Choose start frames with enough parallax.
  • Pure rotation. A rotation without translation gives no depth, and the essential matrix is not defined. The first motion must have a translation.
  • Planar scenes. For points on a plane, the five-point problem has a twofold ambiguity. Score over more views or test a homography.
  • Scale from one step. The whole monocular run takes its scale from ∣t2∣|t_2|. If that step is wrong, all distances are wrong by the same factor.
  • Threshold τ\tau. The inlier threshold is a tuned design choice. With no noise a tight value keeps wrong points out; with noise it must be a few times σ\sigma. A wrong match that lands close to a consistent position cannot be found by any threshold.
  • Firewall spacing. A small ff limits how far an error can pass but also shortens the baselines. The spacing is a heuristic.

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()
nister_visual_odometry.py 497 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nister-visual-odometry/. The authors are listed in prov/RM5DZP.jsonl.
"""Visual odometry of Nister, Naroditsky and Bergen (CVPR 2004).

The input is a set of feature tracks: for each frame, a dict from a track id
to a point (x, y) in normalized image coordinates x = K^-1 (u, v, 1). The
corner detection and the matching that build the tracks are outside this
file. A pose (R, t) maps world points into the camera: X_c = R X_w + t. The
world frame is the camera of frame 0.

Monocular: preemptive RANSAC over five-point hypotheses between frames 0
and 2 gives the first motion with |t| = 1. Points are triangulated, and
every later frame is placed by preemptive RANSAC over P3P hypotheses,
followed by Gauss-Newton on the reprojection error. A firewall every f
frames stops old frames from being used in new triangulations.

Stereo: each rectified stereo pair gives 3D points with a metric scale, and
P3P against the next left image gives the motion between two frames.

The five-point solver is the method of the five-point-algorithm page,
repeated here in short form so that this file is complete.
"""

from __future__ import annotations

import math
import random
from typing import Callable, Dict, List, Optional, Sequence, Tuple

from cvla import cross, det, dot, eye, matvec, mul, norm, nullvec, polyroots_real, scale, skew, solve, svd, transpose

Matrix = List[List[float]]
Vector = List[float]
Pose = Tuple[Matrix, Vector]
Point2 = Tuple[float, float]

# ------------------------------------------------------------ rigid motion


def so3_exp(w: Sequence[float]) -> Matrix:
    """The rotation exp([w]_x), by the Rodrigues formula."""
    th = norm(w)
    k = skew(w)
    kk = mul(k, k)
    if th < 1e-12:
        a, b = 1.0, 0.5
    else:
        a, b = math.sin(th) / th, (1.0 - math.cos(th)) / (th * th)
    i3 = eye(3)
    return [[i3[r][c] + a * k[r][c] + b * kk[r][c] for c in range(3)] for r in range(3)]


def transform(pose: Pose, X: Sequence[float]) -> Vector:
    """R X + t."""
    R, t = pose
    return [a + b for a, b in zip(matvec(R, X), t)]


def compose(a: Pose, b: Pose) -> Pose:
    """The pose that applies b first and then a."""
    return mul(a[0], b[0]), transform(a, b[1])


def rotation_angle(R1: Matrix, R2: Matrix) -> float:
    """The angle of R1^T R2 in radians. It equals arccos((tr(R1^T R2) - 1) / 2),
    but the form 2 asin(|R1 - R2|_F / sqrt(8)) keeps small angles accurate."""
    d = math.sqrt(sum((R1[r][c] - R2[r][c]) ** 2 for r in range(3) for c in range(3)))
    return 2.0 * math.asin(min(1.0, d / math.sqrt(8.0)))


def kabsch(src: Sequence[Sequence[float]], dst: Sequence[Sequence[float]]) -> Pose:
    """The rotation R and translation t that minimize sum |R src_i + t - dst_i|^2,
    with the sign correction that keeps det R = 1."""
    n = len(src)
    cs = [sum(p[k] for p in src) / n for k in range(3)]
    cd = [sum(p[k] for p in dst) / n for k in range(3)]
    h = [[sum((src[i][r] - cs[r]) * (dst[i][c] - cd[c]) for i in range(n)) for c in range(3)] for r in range(3)]
    u, _, v = svd(h)
    d = 1.0 if det(mul(v, transpose(u))) > 0 else -1.0
    R = mul(mul(v, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, d]]), transpose(u))
    return R, [cd[k] - dot(R[k], cs) for k in range(3)]


def project(pose: Pose, X: Sequence[float]) -> Optional[Point2]:
    """The normalized image point of X, or None if X is not in front."""
    xc = transform(pose, X)
    if xc[2] <= 1e-12:
        return None
    return xc[0] / xc[2], xc[1] / xc[2]


def reproj_err2(pose: Pose, X: Sequence[float], x: Point2) -> float:
    """The squared reprojection error, or infinity behind the camera."""
    p = project(pose, X)
    if p is None:
        return math.inf
    return (p[0] - x[0]) ** 2 + (p[1] - x[1]) ** 2


# --------------------------------------------------------- triangulation


def triangulate(poses: Sequence[Pose], obs: Sequence[Point2]) -> Vector:
    """Linear triangulation: the null vector of the rows x P3 - P1 and
    y P3 - P2 of every view, with P = [R | t]."""
    rows = []
    for (R, t), (x, y) in zip(poses, obs):
        p = [R[0] + [t[0]], R[1] + [t[1]], R[2] + [t[2]]]
        rows.append([x * p[2][k] - p[0][k] for k in range(4)])
        rows.append([y * p[2][k] - p[1][k] for k in range(4)])
    h = nullvec(rows)
    if abs(h[3]) < 1e-15:
        return [math.inf, math.inf, math.inf]
    return [h[0] / h[3], h[1] / h[3], h[2] / h[3]]


def checked_point(poses: Sequence[Pose], obs: Sequence[Point2], tau: float) -> Optional[Vector]:
    """Triangulate, and keep the point only if it is in front of every view
    with a reprojection error of at most tau."""
    X = triangulate(poses, obs)
    if not all(math.isfinite(c) for c in X):
        return None
    for pose, x in zip(poses, obs):
        if reproj_err2(pose, X, x) > tau * tau:
            return None
    return X


# ---------------------------------------------------- five-point solver

_MONO = [(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 _padd(p, q, c=1.0):
    out = dict(p)
    for k, v in q.items():
        out[k] = out.get(k, 0.0) + c * v
    return out


def _pmul(p, q):
    out = {}
    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 _pmat(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 _zadd(p, q, c=1.0):
    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, q):
    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, z):
    s = 0.0
    for c in reversed(p):
        s = s * z + c
    return s


def _cubic_residual(M, x, y, z):
    m = [x ** a * y ** b * z ** c for a, b, c in _MONO]
    return [sum(p * q for p, q in zip(row, m)) for row in M]


def _polish(M, x, y, z):
    r = _cubic_residual(M, x, y, z)
    for _ in range(4):
        cols = []
        for k in range(3):
            d = []
            for e in _MONO:
                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 = [[dot(cols[i], cols[j]) for j in range(3)] for i in range(3)]
        try:
            s = solve(jtj, [-dot(cols[i], r) for i in range(3)])
        except ValueError:
            break
        nr = _cubic_residual(M, x + s[0], y + s[1], z + s[2])
        if norm(nr) >= norm(r):
            break
        x, y, z, r = x + s[0], y + s[1], z + s[2], nr
    return x, y, z


def canonical(E: Matrix) -> Matrix:
    """E with Frobenius norm 1 and its largest entry (in absolute value) positive."""
    big = max((v for row in E for v in row), key=abs)
    return scale(E, (1.0 if big > 0 else -1.0) / norm(E))


def five_point(x1: Sequence[Point2], x2: Sequence[Point2]) -> List[Matrix]:
    """Every essential matrix E with x2^T E x1 = 0 on 5 point pairs."""
    a = [[q * p for q in (b[0], b[1], 1.0) for p in (c[0], c[1], 1.0)] for c, b in zip(x1, x2)]
    a += [[0.0] * 9 for _ in range(9 - len(a))]
    _, _, v = svd(a)
    X, Y, Z, W = [[[v[3 * i + j][col] for j in range(3)] for i in range(3)] for col in range(5, 9)]
    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)]
    eet = _pmat(E, [[E[j][i] for j in range(3)] for i in range(3)])
    tr = _padd(_padd(eet[0][0], eet[1][1]), eet[2][2])
    eete = _pmat(eet, E)
    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 = [d] + [_padd({k: 2.0 * w for k, w in eete[i][j].items()}, _pmul(tr, E[i][j]), -1.0)
                  for i in range(3) for j in range(3)]
    M = [[r.get(m, 0.0) for m in _MONO] for r in rows]
    try:
        C = solve([row[:10] for row in M], [row[10:] for row in M])
    except ValueError:
        return []

    def parts(c):
        return [[c[2], c[1], c[0]], [c[5], c[4], c[3]], [c[9], c[8], c[7], c[6]]]

    B = []
    for r in range(3):
        top, bot = parts(C[4 + 2 * r]), parts(C[5 + 2 * r])
        B.append([_zadd(top[k], [0.0] + bot[k], -1.0) for k in range(3)])

    def minor(p, q, r, s):
        return _zadd(_zmul(p, s), _zmul(q, r), -1.0)

    detb = _zadd(_zadd(_zmul(B[0][0], minor(B[1][1], B[1][2], B[2][1], B[2][2])),
                       _zmul(B[0][1], minor(B[1][0], B[1][2], B[2][0], B[2][2])), -1.0),
                 _zmul(B[0][2], minor(B[1][0], B[1][1], B[2][0], B[2][1])))
    out = []
    for z in polyroots_real(list(reversed(detb))):
        bz = [[_zeval(p, z) for p in row] for row in B]
        w = max([cross(bz[0], bz[1]), cross(bz[0], bz[2]), cross(bz[1], bz[2])], key=norm)
        if abs(w[2]) <= 1e-12 * norm(w):
            continue
        x, y, z = _polish(M, w[0] / w[2], w[1] / w[2], z)
        out.append(canonical([[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)]))
    return out


def sampson_err2(E: Matrix, x1: Point2, x2: Point2) -> float:
    """The squared Sampson distance of a pair to the epipolar constraint."""
    p, q = [x1[0], x1[1], 1.0], [x2[0], x2[1], 1.0]
    ep, etq = matvec(E, p), matvec(transpose(E), q)
    den = ep[0] ** 2 + ep[1] ** 2 + etq[0] ** 2 + etq[1] ** 2
    return dot(q, ep) ** 2 / den if den > 0 else math.inf


def decompose_essential(E: Matrix, x1: Sequence[Point2], x2: Sequence[Point2]) -> Pose:
    """The pair (R, t), |t| = 1, of the four candidates that puts the most
    pairs in front of both cameras (a majority vote)."""
    u, _, v = svd(E)
    if det(u) < 0:
        u = scale(u, -1.0)
    if det(v) < 0:
        v = scale(v, -1.0)
    w = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
    t = [u[0][2], u[1][2], u[2][2]]
    cands = []
    for R in (mul(mul(u, w), transpose(v)), mul(mul(u, transpose(w)), transpose(v))):
        for s in (1.0, -1.0):
            cands.append((R, scale(t, s)))
    first = (eye(3), [0.0, 0.0, 0.0])
    best, best_count = cands[0], -1
    for cand in cands:
        count = 0
        for p, q in zip(x1, x2):
            X = triangulate([first, cand], [p, q])
            if all(math.isfinite(c) for c in X) and X[2] > 0 and transform(cand, X)[2] > 0:
                count += 1
        if count > best_count:
            best, best_count = cand, count
    return best


# ------------------------------------------------------------------ P3P


def _lmul(p, q):
    return _zmul(p, q)


def p3p(bearings: Sequence[Sequence[float]], points: Sequence[Sequence[float]]) -> List[Pose]:
    """Grunert's P3P: every pose (R, t) with R X_i + t on the ray of bearing
    f_i at a positive distance, for 3 points. At most 4 solutions."""
    f = [scale(b, 1.0 / norm(b)) for b in bearings]
    X = [list(map(float, p)) for p in points]
    a2 = norm([X[1][k] - X[2][k] for k in range(3)]) ** 2
    b2 = norm([X[0][k] - X[2][k] for k in range(3)]) ** 2
    c2 = norm([X[0][k] - X[1][k] for k in range(3)]) ** 2
    ca, cb, cg = dot(f[1], f[2]), dot(f[0], f[2]), dot(f[0], f[1])
    q = [1.0, -2.0 * cb, 1.0]
    num = _zadd([b2, 0.0, -b2], q, a2 - c2)
    den = [2.0 * b2 * cg, -2.0 * b2 * ca]
    quartic = _zadd(_zadd(scale(_lmul(num, num), b2), scale(_lmul(num, den), -2.0 * b2 * cg)),
                    _lmul([b2 - c2, 2.0 * c2 * cb, -c2], _lmul(den, den)))
    out = []
    for v in polyroots_real(list(reversed(quartic))):
        dv = _zeval(den, v)
        qv = _zeval(q, v)
        if v <= 0 or abs(dv) < 1e-14 or qv <= 0:
            continue
        u = _zeval(num, v) / dv
        if u <= 0:
            continue
        s1 = math.sqrt(b2 / qv)
        cam = [scale(f[0], s1), scale(f[1], u * s1), scale(f[2], v * s1)]
        out.append(kabsch(X, cam))
    return out


# ------------------------------------------- preemptive scoring and refinement


def preemptive_select(hyps: Sequence, n_obs: int, err2: Callable[[object, int], float],
                      tau: float, block: int, rng: random.Random):
    """Preemptive scoring: the observations are taken in a random order, in
    blocks; after each block only the better half of the hypotheses is kept.
    The score is the truncated quadratic sum of min(e^2, tau^2)."""
    if not hyps:
        return None
    order = list(range(n_obs))
    rng.shuffle(order)
    alive = list(range(len(hyps)))
    score = [0.0] * len(hyps)
    pos = 0
    while pos < n_obs and len(alive) > 1:
        for i in order[pos:pos + block]:
            for h in alive:
                score[h] += min(err2(hyps[h], i), tau * tau)
        pos += block
        alive.sort(key=lambda h: score[h])
        alive = alive[:max(1, len(alive) // 2)]
    return hyps[min(alive, key=lambda h: score[h])]


def pose_residual(pose: Pose, X: Sequence[float], x: Point2) -> Vector:
    xc = transform(pose, X)
    return [xc[0] / xc[2] - x[0], xc[1] / xc[2] - x[1]]


def pose_jacobian(pose: Pose, X: Sequence[float]) -> Matrix:
    """The 2 x 6 Jacobian of the residual for the update of apply_update,
    with the parameters (w, dt)."""
    xc = transform(pose, X)
    z = xc[2]
    dp = [[1.0 / z, 0.0, -xc[0] / (z * z)], [0.0, 1.0 / z, -xc[1] / (z * z)]]
    dw = scale(skew(xc), -1.0)
    return [[dot(dp[r], [dw[0][c], dw[1][c], dw[2][c]]) for c in range(3)] + dp[r] for r in range(2)]


def apply_update(pose: Pose, delta: Sequence[float]) -> Pose:
    """(exp(w) R, exp(w) t + dt) for delta = (w, dt)."""
    E = so3_exp(delta[:3])
    R, t = pose
    return mul(E, R), [a + b for a, b in zip(matvec(E, t), delta[3:])]


def refine_pose(pose: Pose, pts: Sequence[Sequence[float]], obs: Sequence[Point2],
                iters: int = 10) -> Tuple[Pose, List[float]]:
    """Gauss-Newton on sum |pi(R X + t) - x|^2. A step is kept only if it
    lowers the cost. Returns the pose and the cost after each kept step."""
    def cost(p):
        return sum(sum(r * r for r in pose_residual(p, X, x)) for X, x in zip(pts, obs))
    c = cost(pose)
    history = [c]
    for _ in range(iters):
        h = [[0.0] * 6 for _ in range(6)]
        g = [0.0] * 6
        for X, x in zip(pts, obs):
            j = pose_jacobian(pose, X)
            r = pose_residual(pose, X, x)
            for a in range(6):
                g[a] -= j[0][a] * r[0] + j[1][a] * r[1]
                for b in range(6):
                    h[a][b] += j[0][a] * j[0][b] + j[1][a] * j[1][b]
        try:
            step = solve(h, g)
        except ValueError:
            break
        cand = apply_update(pose, step)
        cc = cost(cand)
        if not cc < c:
            break
        pose, c = cand, cc
        history.append(c)
    return pose, history


def resection(pts: Sequence[Sequence[float]], obs: Sequence[Point2], tau: float,
              n_hyp: int, block: int, rng: random.Random) -> Optional[Pose]:
    """Preemptive RANSAC over P3P hypotheses, then Gauss-Newton on the inliers."""
    n = len(pts)
    if n < 4:
        return None
    hyps: List[Pose] = []
    for _ in range(n_hyp):
        idx = rng.sample(range(n), 3)
        hyps += p3p([[obs[i][0], obs[i][1], 1.0] for i in idx], [pts[i] for i in idx])
    best = preemptive_select(hyps, n, lambda h, i: reproj_err2(h, pts[i], obs[i]), tau, block, rng)  # @line L6
    if best is None:
        return None
    inl = [i for i in range(n) if reproj_err2(best, pts[i], obs[i]) <= tau * tau]
    if len(inl) < 3:
        return best
    pose, _ = refine_pose(best, [pts[i] for i in inl], [obs[i] for i in inl])  # @line L7
    return pose


# ------------------------------------------------------------- the systems


def mono_vo(tracks: Sequence[Dict[int, Point2]], firewall_every: int = 4, tau: float = 0.004,
            n_hyp: int = 20, block: int = 10, seed: int = 0) -> List[Pose]:
    """Monocular visual odometry. tracks[k] maps a track id to its normalized
    point in frame k. Returns one pose per frame; the first is (I, 0) and the
    second camera of the start triplet (frame 2) is at distance 1."""
    rng = random.Random(seed)
    n = len(tracks)
    poses: List[Optional[Pose]] = [None] * n
    poses[0] = (eye(3), [0.0, 0.0, 0.0])  # @line L1
    ids = sorted(set(tracks[0]) & set(tracks[2]))
    x1 = [tracks[0][i] for i in ids]
    x2 = [tracks[2][i] for i in ids]
    hyps: List[Matrix] = []
    for _ in range(n_hyp):
        s = rng.sample(range(len(ids)), 5)
        hyps += five_point([x1[i] for i in s], [x2[i] for i in s])  # @line L2
    E = preemptive_select(hyps, len(ids), lambda h, i: sampson_err2(h, x1[i], x2[i]), tau, block, rng)  # @line L2
    inl = [i for i in range(len(ids)) if sampson_err2(E, x1[i], x2[i]) <= tau * tau]
    poses[2] = decompose_essential(E, [x1[i] for i in inl], [x2[i] for i in inl])  # @line L3
    world: Dict[int, Vector] = {}
    for i in inl:
        X = checked_point([poses[0], poses[2]], [x1[i], x2[i]], tau)  # @line L4
        if X is not None:
            world[ids[i]] = X  # @line L4
    firewall = 0  # @line L4
    for k in [1] + list(range(3, n)):  # @line L5
        seen = [i for i in tracks[k] if i in world]
        pose = resection([world[i] for i in seen], [tracks[k][i] for i in seen], tau, n_hyp, block, rng)  # @line L6
        if pose is None:
            raise ValueError("frame %d could not be placed" % k)
        poses[k] = pose  # @line L7
        for tid, x in tracks[k].items():  # @line L8
            first = next((j for j in range(firewall, k) if poses[j] is not None and tid in tracks[j]), None)  # @line L9
            if first is not None and k - first >= 2:  # @line L10
                X = checked_point([poses[first], pose], [tracks[first][tid], x], tau)
                if X is not None:
                    world[tid] = X  # @line L10
        if k % firewall_every == 0:  # @line L11
            firewall = k  # @line L11
    return poses  # @line L12


def stereo_vo(left: Sequence[Dict[int, Point2]], right: Sequence[Dict[int, Point2]], baseline: float,
              tau: float = 0.004, n_hyp: int = 15, block: int = 10, seed: int = 0) -> List[Pose]:
    """Stereo visual odometry on a rectified pair: the right camera is the left
    one moved by baseline along +x. Points from the pair at frame k - 1 and
    P3P in the left image k give the motion; the poses are chained."""
    rng = random.Random(seed)
    rig = [(eye(3), [0.0, 0.0, 0.0]), (eye(3), [-baseline, 0.0, 0.0])]
    poses: List[Pose] = [(eye(3), [0.0, 0.0, 0.0])]
    for k in range(1, len(left)):
        pts, obs = [], []
        for tid, xl in left[k - 1].items():
            if tid in right[k - 1] and tid in left[k]:
                X = checked_point(rig, [xl, right[k - 1][tid]], tau)
                if X is not None:
                    pts.append(X)
                    obs.append(left[k][tid])
        rel = resection(pts, obs, tau, n_hyp, block, rng)
        if rel is None:
            raise ValueError("frame %d could not be placed" % k)
        poses.append(compose(rel, poses[-1]))
    return poses
test_nister_visual_odometry.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nister-visual-odometry/. The authors are listed in prov/RM5DZP.jsonl.
import math
import random

from cvla import cross, matvec, mul, norm, skew, svd, transpose
from nister_visual_odometry import (
    apply_update, canonical, decompose_essential, five_point, mono_vo, p3p, pose_jacobian, pose_residual,
    preemptive_select, project, refine_pose, resection, rotation_angle, so3_exp, stereo_vo, transform)

F = 500.0  # focal length in pixels; the image is 640 x 480


def inside(p):
    return p is not None and abs(p[0]) <= 320.0 / F and abs(p[1]) <= 240.0 / F


def make_poses(n):
    poses = []
    for k in range(n):
        R = so3_exp([0.01 * k, 0.03 * k, 0.005 * k])
        C = [0.15 * k, 0.02 * k, 0.35 * k]
        poses.append((R, [-v for v in matvec(R, C)]))
    return poses


def make_scene(rng, n_frames, n_points, baseline=None):
    poses = make_poses(n_frames)
    cams = list(poses)
    if baseline is not None:
        cams += [(R, [t[0] - baseline, t[1], t[2]]) for R, t in poses]
    pts = []
    while len(pts) < n_points:
        X = [rng.uniform(-5.0, 5.0), rng.uniform(-3.5, 3.5), rng.uniform(8.0, 16.0)]
        if all(inside(project(c, X)) for c in cams):
            pts.append(X)
    return poses, pts


def observe(rng, pose, pts, outlier_rate=0.0, sigma_px=0.0):
    out = {}
    for i, X in enumerate(pts):
        if rng.random() < outlier_rate:
            out[i] = (rng.uniform(-0.64, 0.64), rng.uniform(-0.48, 0.48))
            continue
        x, y = project(pose, X)
        out[i] = (x + rng.gauss(0.0, sigma_px / F), y + rng.gauss(0.0, sigma_px / F))
    return out


def test_p3p_returns_true_pose():
    rng = random.Random(1)
    for _ in range(20):
        pose = (so3_exp([rng.uniform(-0.5, 0.5) for _ in range(3)]), [rng.uniform(-1, 1) for _ in range(3)])
        R, t = pose
        pts = []
        while len(pts) < 3:
            X = [rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(4, 8)]
            if transform(pose, X)[2] > 0.5:
                pts.append(X)
        bearings = [transform(pose, X) for X in pts]
        sols = p3p(bearings, pts)
        assert 1 <= len(sols) <= 4
        for s in sols:
            assert abs(mul(transpose(s[0]), s[0])[0][0] - 1.0) < 1e-9
            for X, b in zip(pts, bearings):
                xc = transform(s, X)
                assert xc[2] > 0
                assert norm(cross(xc, b)) <= 1e-7 * norm(xc) * norm(b)
        assert any(rotation_angle(s[0], R) < 1e-8 and norm([a - b for a, b in zip(s[1], t)]) < 1e-8 for s in sols)


def test_five_point_solutions_and_truth():
    rng = random.Random(2)
    for _ in range(5):
        R = so3_exp([rng.uniform(-0.3, 0.3) for _ in range(3)])
        t = [rng.uniform(-1, 1) for _ in range(3)]
        pts = [[rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(4, 8)] for _ in range(5)]
        x1 = [(X[0] / X[2], X[1] / X[2]) for X in pts]
        x2 = [project((R, t), X) for X in pts]
        sols = five_point(x1, x2)
        assert sols
        for E in sols:
            s = svd(E)[1]
            assert abs(s[0] - s[1]) <= 1e-8 and s[2] <= 1e-8
            for p, q in zip(x1, x2):
                assert abs(sum(q2 * sum(E[i][j] * p2 for j, p2 in enumerate((p[0], p[1], 1.0)))
                               for i, q2 in enumerate((q[0], q[1], 1.0)))) <= 1e-9
        truth = canonical(mul(skew(t), R))
        assert min(norm([[a - b for a, b in zip(r1, r2)] for r1, r2 in zip(E, truth)]) for E in sols) <= 1e-8
        R2, t2 = decompose_essential(truth, x1, x2)
        assert rotation_angle(R2, R) <= 1e-8
        assert norm([a - b / norm(t) for a, b in zip(t2, t)]) <= 1e-8


def test_preemptive_select_keeps_best():
    rng = random.Random(3)
    data = [2.0 + rng.gauss(0.0, 0.01) for _ in range(40)] + [rng.uniform(-50, 50) for _ in range(10)]
    hyps = [0.0, 1.0, 2.0, 3.0, -5.0, 10.0, 2.5, 1.5]
    best = preemptive_select(hyps, len(data), lambda h, i: (h - data[i]) ** 2, 0.2, 5, rng)
    assert best == 2.0


def test_pose_jacobian_and_refinement():
    rng = random.Random(4)
    true = (so3_exp([0.1, -0.2, 0.05]), [0.3, -0.1, 0.5])
    pts = [[rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(4, 8)] for _ in range(20)]
    obs = [project(true, X) for X in pts]
    start = apply_update(true, [0.02, -0.01, 0.015, 0.05, -0.04, 0.03])
    h = 1e-6
    for X, x in zip(pts[:5], obs[:5]):
        j = pose_jacobian(start, X)
        for c in range(6):
            d = [0.0] * 6
            d[c] = h
            rp = pose_residual(apply_update(start, d), X, x)
            d[c] = -h
            rm = pose_residual(apply_update(start, d), X, x)
            for r in range(2):
                assert abs((rp[r] - rm[r]) / (2 * h) - j[r][c]) <= 1e-6 * max(1.0, abs(j[r][c]))
    pose, hist = refine_pose(start, pts, obs)
    assert all(b < a for a, b in zip(hist, hist[1:]))
    assert rotation_angle(pose[0], true[0]) <= 1e-6
    assert norm([a - b for a, b in zip(pose[1], true[1])]) <= 1e-6


def test_resection_with_outliers():
    rng = random.Random(5)
    true = (so3_exp([0.05, 0.1, -0.02]), [0.2, 0.1, -0.3])
    pts = [[rng.uniform(-3, 3), rng.uniform(-2, 2), rng.uniform(6, 12)] for _ in range(40)]
    bad = set(rng.sample(range(40), 10))
    obs = [(rng.uniform(-0.6, 0.6), rng.uniform(-0.4, 0.4)) if i in bad else project(true, X) for i, X in enumerate(pts)]
    pose = resection(pts, obs, 0.004, 15, 8, rng)
    assert rotation_angle(pose[0], true[0]) <= 1e-6
    assert norm([a - b for a, b in zip(pose[1], true[1])]) <= 1e-6
    found = {i for i in range(40) if norm([a - b for a, b in zip(project(pose, pts[i]), obs[i])]) <= 0.004}
    assert found == set(range(40)) - bad


def test_monocular_sequence_up_to_scale():
    rng = random.Random(6)
    poses, pts = make_scene(rng, 8, 60)
    tracks = [observe(rng, p, pts, outlier_rate=0.1) for p in poses]
    est = mono_vo(tracks, firewall_every=4, seed=7)
    s = norm(est[2][1]) / norm(poses[2][1])
    for (R, t), (Re, te) in zip(poses, est):
        assert rotation_angle(R, Re) <= 1e-6
        assert norm([a - s * b for a, b in zip(te, t)]) <= 1e-6 * max(1.0, s * norm(t))


def test_stereo_sequence_exact_and_noisy():
    rng = random.Random(8)
    b = 0.5
    poses, pts = make_scene(rng, 6, 50, baseline=b)
    right = [(R, [t[0] - b, t[1], t[2]]) for R, t in poses]
    left_obs = [observe(rng, p, pts, outlier_rate=0.1) for p in poses]
    right_obs = [observe(rng, p, pts, outlier_rate=0.1) for p in right]
    # Without noise a tight threshold (0.5 pixel) keeps out wrong points that
    # an outlier near the epipolar line can create.
    est = stereo_vo(left_obs, right_obs, b, tau=0.001, seed=9)
    for (R, t), (Re, te) in zip(poses, est):
        assert rotation_angle(R, Re) <= 1e-6
        assert norm([x - y for x, y in zip(te, t)]) <= 1e-6
    # sigma = 0.5 pixel: rotation error below 1 degree and position error below
    # 5 percent of the path length after 5 steps.
    left_obs = [observe(rng, p, pts, sigma_px=0.5) for p in poses]
    right_obs = [observe(rng, p, pts, sigma_px=0.5) for p in right]
    est = stereo_vo(left_obs, right_obs, b, seed=10)
    path = norm([0.15 * 5, 0.02 * 5, 0.35 * 5])
    for (R, t), (Re, te) in zip(poses, est):
        assert rotation_angle(R, Re) <= math.radians(1.0)
        c_true = matvec(transpose(R), [-v for v in t])
        c_est = matvec(transpose(Re), [-v for v in te])
        assert norm([x - y for x, y in zip(c_true, c_est)]) <= 0.05 * path

History

Nistér, Naroditsky and Bergen presented the system at CVPR 2004 and used the name "visual odometry" for it, by analogy with wheel odometry. It built on Nistér's five-point solver and his preemptive RANSAC of 2003, both made for live structure from motion. The journal paper of 2006 in the Journal of Field Robotics described the use on ground vehicles. Earlier work, from Moravec in 1980 to the stereo systems of the Mars rovers, had estimated the motion of a robot from stereo images, mostly by aligning 3D points. The tutorial of Scaramuzza and Fraundorfer (2011) gives this history and compares the 3D-to-3D and 3D-to-2D schemes.

References

  1. David Nistér, Oleg Naroditsky and James Bergen, Visual odometry, Proceedings of the IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR 2004), volume 1, 652-659, the whole paper (corner detection and matching, the monocular scheme with the five-point solver and the three-point resection in preemptive RANSAC, the firewall, and the stereo scheme)
  2. David Nistér, Oleg Naroditsky and James Bergen, Visual odometry for ground vehicle applications, Journal of Field Robotics 23(1), 2006, 3-20, the journal version of the same system, with the runs on ground vehicles
  3. Davide Scaramuzza and Friedrich Fraundorfer, Visual odometry, Part I: the first 30 years and fundamentals, IEEE Robotics and Automation Magazine 18(4), 2011, 80-92, the history of the term, the comparison of 3D-to-3D and 3D-to-2D motion estimation, and the relative scale of monocular visual odometry
  4. David Nistér, Preemptive RANSAC for live structure and motion estimation, Proceedings of the Ninth IEEE International Conference on Computer Vision (ICCV 2003), 199-206, the preemptive scoring of hypotheses that the system uses
  5. David Nistér, An efficient solution to the five-point relative pose problem, IEEE Transactions on Pattern Analysis and Machine Intelligence 26(6), 2004, the five-point solver that gives the motion hypotheses of the monocular scheme

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