Algorithm Search⌘K

Algorithmadvanced

Global structure from motion

Also called global SfM.

Solve for all camera rotations at once by rotation averaging, then all positions by translation averaging, then triangulate and bundle adjust once.

Time
O(N m + N^3) total
Space
O(N^2 + m) extra
Where
E = the number of edges of the view graph; N = the number of images; m = the number of observations
Properties
randomizediterativelocalnot monotoneiterative
Origin
Venu Madhav Govindu, Daniel Martinec, Tomas Pajdla, Pierre Moulon, Kyle Wilson, Noah Snavely, 2013

Global structure from motion solves the structure from motion problem for calibrated cameras by estimating all cameras at once, instead of one at a time as incremental structure from motion does. It first estimates the relative pose of every image pair with enough matches, which gives the view graph. Then it splits the camera poses into two parts. Rotation averaging finds all absolute rotations from the relative rotations of the edges. With the rotations known, each relative translation gives the direction from one camera center to another, and translation averaging finds all centers from these directions. Finally it triangulates every track with the fixed cameras and runs one bundle adjustment. Each step treats all images the same way, so the errors spread evenly over the scene, and the method needs only a few large solves, which makes it much faster than the incremental method on large photo collections. The weak step is translation averaging, which is sensitive to wrong edges and to cameras on a line.

In plain words

The incremental method builds the model one photo at a time. The global method looks at all photos together. First, for every pair of photos that overlap, it works out how the two cameras stand compared with each other. Then it answers the question in two parts. Which way does each camera point? It picks the directions that agree best with all the pairs at once. Where does each camera stand? With the directions known, each pair says in which direction one camera sees the other, and the method picks the positions that agree best with these directions. Last, it places the points in 3D and polishes everything once.

The problem

Input. An intrinsic matrix KK shared by all images, the feature tracks of NN images, a threshold τ\tau on the reprojection error in pixels, a threshold α\alpha on the disagreement of a relative rotation, a minimum number of inliers per edge, and a random seed.

Output. A pose (Ri,ti)(R_i, t_i) with Xc=RiX+tiX_c = R_i X + t_i for each image of the largest connected part of the view graph, and a point XjX_j for each track that could be triangulated. The first image has R=IR = I and t=0t = 0, and the scale is arbitrary, set by the normalization of the centers.

Conventions. The relative pose of an edge (i,j)(i, j) is Xj=RijXi+tijX_j = R_{ij} X_i + t_{ij}, so Rij=RjRiTR_{ij} = R_j R_i^{\mathsf T} and tij=−Rj(cj−ci)t_{ij} = -R_j (c_j - c_i) for the centers ci=−RiTtic_i = -R_i^{\mathsf T} t_i. With known rotations, the unit direction from cic_i to cjc_j is vij=−RjTtij/∥tij∥v_{ij} = -R_j^{\mathsf T} t_{ij} / \|t_{ij}\|.

The algorithm

  1. GLOBAL-SFM(K, tracks, τ, α)
  2. 1for each image pair with enough common tracks: (R_ij, t_ij) <- RANSAC on the essential matrix; keep it as an edge if it has enough inliers
  3. 2R <- robust Lie-algebraic rotation averaging on the edges of the largest connected part (an L1 start, then Geman-McClure weights)
  4. 3remove each edge with angle(R_ij, R_j R_i^T) > α, and stop if the graph is no longer connected
  5. 4for each edge: v_ij <- -R_j^T t_ij / ||t_ij||
  6. 5c <- the eigenvector of the smallest eigenvalue of the matrix of Σ ||(I - v_ij v_ij^T)(c_j - c_i)||², with c_1 = 0 and the sign that makes Σ v_ij · (c_j - c_i) > 0
  7. 6for each image k: t_k <- -R_k c_k
  8. 7triangulate each track from its registered views; keep the views with error below 10 τ, refit once, keep it if 2 views remain
  9. 8bundle adjust all cameras and points with the first camera fixed
  10. 9drop observations with error above τ and points with fewer than 2 observations, then bundle adjust again
  11. 10return the cameras, the points and the kept observations

Line L1 builds the view graph with the eight-point algorithm inside RANSAC and the essential matrix decomposition, as in the first step of the incremental method. Line L2 is Lie-algebraic rotation averaging from a breadth-first tree start, 30 iterations with L1L_1 weights and 30 with Geman-McClure weights. Line L3 removes the edges whose relative rotations disagree with the averaged ones, since these edges likely have wrong translations too. Line L5 is the linear form of translation averaging: the matrix is a block Laplacian of size 3(N−1)3(N - 1) after the row and column of c1c_1 are removed, and the constraint ∑∥ck∥2=1\sum \|c_k\|^2 = 1 makes the minimum an eigenvector. Line L7 uses a loose gate of 10τ10 \tau, because the cameras are not yet refined. Lines L8 and L9 use Levenberg-Marquardt with the points eliminated by the Schur complement.

Example

The reference test uses 5 cameras on a sphere of radius 3, all looking at the origin, with f=800f = 800 px, and 40 points in a cube of size 2. Each point is seen by each camera with probability 0.8. Gaussian noise of 0.5 px is added, and 5% of the observations are replaced by random pixels. With τ=3\tau = 3 px and α=0.1\alpha = 0.1 rad:

  • There are 161 observations. Line L1 finds all 10 image pairs as edges, with 18 to 27 inliers each.
  • Line L3 keeps all 10 edges.
  • After line L9, the result has 5 cameras, 35 points and 134 kept observations. The largest reprojection error is 1.05 px and the root mean square error is 0.47 px.
  • After the best similarity to the truth, the largest point error is 0.027 units, the largest center error is 0.0025 units, and the largest rotation error is 0.0019 rad.

A second test shows the edge filter. Six cameras form a complete graph with exact relative poses, and the relative rotation of the edge (1,4)(1, 4) is turned by an extra 0.5 rad. Robust averaging still finds all rotations within 2⋅10−32 \cdot 10^{-3} rad, and line L3 removes the edge (1,4)(1, 4) and only that edge. A third test shows why the graph needs loops: for 4 cameras on a path, the matrix of line L5 has 3 zero eigenvalues, so the centers are not fixed, and closing the path into a cycle leaves 1, the scale. These are benchmark results of the reference tests.

Correctness

On exact data, the method returns the true cameras and points up to a similarity, if each image pair of the view graph satisfies the conditions of the eight-point method, the graph is parallel rigid for the true centers, and each track is seen from two centers that are not on one line with its point (theorem). The steps are: line L1 gives exact relative poses with ∥tij∥=1\|t_{ij}\| = 1; the tree start of line L2 fits every edge exactly, so the reweighted iterations do not move it; line L3 keeps every edge; the directions of line L4 are exact; under parallel rigidity the matrix of line L5 has a one-dimensional null space that holds the true centers; and triangulation and bundle adjustment then change nothing. The proof below gives the details. Each bundle adjustment never raises its cost (theorem). With noise and outliers there is no guarantee: rotation averaging and bundle adjustment find local minima, and the linear translation step can pull cameras together (heuristic).

Proof: Global SfM recovers exact data up to a similarity when the view graph is parallel rigidfull

We use the notation of the page and exact arithmetic, as in the real RAM model. The true cameras are (Rk∗,tk∗)(R_k^*, t_k^*) with centers ck∗=−(Rk∗)Ttk∗c_k^* = -(R_k^*)^{\mathsf T} t_k^*, the true points are Xj∗X_j^*, and the observations are exact projections with positive depths. Index the images of the largest connected part of the view graph by 0,…,N−10, \dots, N - 1, so image 0 is the first one. We assume:

  • (G1) For every image pair that line L1 tests, the conditions of the eight-point method hold as in the proof of incremental structure from motion: every 8 common tracks give a conditioned system with a null space of dimension 1, the two centers differ, and no point lies on the baseline.
  • (G2) Let MM be the matrix of line L5 for the true directions, with the row and column blocks of c0c_0 removed. Its null space has dimension 1. This is the condition that the view graph with the true centers is parallel rigid.
  • (G3) Each track that is triangulated is seen from two centers that do not lie on one line with its point.

Claim. (a) Each bundle adjustment returns a cost no larger than its start cost. (b) Under (G1) to (G3), the output is the truth after the similarity X′=sR0∗(X−c0∗)X' = s R_0^* (X - c_0^*) with s=1/(∑k∥ck∗−c0∗∥2)1/2s = 1 / (\sum_k \|c_k^* - c_0^*\|^2)^{1/2}. That is, Rk=Rk∗(R0∗)TR_k = R_k^* (R_0^*)^{\mathsf T}, ck=sR0∗(ck∗−c0∗)c_k = s R_0^* (c_k^* - c_0^*), tk=−Rkckt_k = -R_k c_k and Xj=sR0∗(Xj∗−c0∗)X_j = s R_0^* (X_j^* - c_0^*).

Proof of (a). Levenberg-Marquardt accepts a trial step only if it lowers the cost strictly, and otherwise raises the damping and tries again, so the cost never rises. □\square

Proof of (b). The target. For each camera, s(Rk∗X+tk∗)=sRk∗(X−ck∗)=Rk∗(R0∗)T sR0∗((X−c0∗)−(ck∗−c0∗))=Rk(X′−ck)=RkX′+tks (R_k^* X + t_k^*) = s R_k^* (X - c_k^*) = R_k^* (R_0^*)^{\mathsf T} \, s R_0^* \big((X - c_0^*) - (c_k^* - c_0^*)\big) = R_k (X' - c_k) = R_k X' + t_k. The camera coordinates are scaled by s>0s > 0, so the projections and the signs of the depths are the same. So the target explains the data, with R0=IR_0 = I and c0=0c_0 = 0.

Line L1. By (G1) and the argument of the incremental proof, each edge (i,j)(i, j) gets the exact relative pose Rij=Rj∗(Ri∗)TR_{ij} = R_j^* (R_i^*)^{\mathsf T}, tij=t^ij/∥t^ij∥t_{ij} = \hat t_{ij} / \|\hat t_{ij}\|, where t^ij=−Rj∗(cj∗−ci∗)\hat t_{ij} = -R_j^* (c_j^* - c_i^*) is the true relative translation. All common tracks are inliers.

Line L2. The tree start chains Rj=RijRiR_j = R_{ij} R_i from R0=IR_0 = I, which gives Rk=Rk∗(R0∗)TR_k = R_k^* (R_0^*)^{\mathsf T} by induction on the depth in the tree. Then every residual log⁡(RjTRijRi)\log(R_j^{\mathsf T} R_{ij} R_i) is log⁡I=0\log I = 0, for tree edges and other edges alike. So the right side bb of every Lie-algebraic step is 0, and since the grounded Laplacian of a connected graph with positive weights is invertible (see the proof of Lie-algebraic rotation averaging), the step is ω=0\omega = 0, with the L1L_1 weights and with the Geman-McClure weights. So line L2 returns Rk=Rk∗(R0∗)TR_k = R_k^* (R_0^*)^{\mathsf T}.

Line L3. Every edge has RjRiT=Rj∗(Ri∗)T=RijR_j R_i^{\mathsf T} = R_j^* (R_i^*)^{\mathsf T} = R_{ij}, so its angle is 0 and no edge is removed. The graph stays connected.

Line L4. For each edge,

vij=−RjTt^ij∥t^ij∥=R0∗(Rj∗)TRj∗(cj∗−ci∗)∥cj∗−ci∗∥=R0∗(cj∗−ci∗)∥cj∗−ci∗∥.v_{ij} = \frac{-R_j^{\mathsf T} \hat t_{ij}}{\|\hat t_{ij}\|} = \frac{R_0^* (R_j^*)^{\mathsf T} R_j^* (c_j^* - c_i^*)}{\|c_j^* - c_i^*\|} = \frac{R_0^* (c_j^* - c_i^*)}{\|c_j^* - c_i^*\|}.

So vijv_{ij} is the unit vector along cj′−ci′c_j' - c_i' for the points ck′=R0∗(ck∗−c0∗)c_k' = R_0^* (c_k^* - c_0^*), and c0′=0c_0' = 0.

Line L5. The matrix MM is a sum of terms ∥(I−vijvijT)(cj−ci)∥2\|(I - v_{ij} v_{ij}^{\mathsf T})(c_j - c_i)\|^2, so it is positive semidefinite, and its smallest eigenvalue is at least 0. Each term is 0 at c′c', because cj′−ci′c_j' - c_i' is parallel to vijv_{ij}, so Mc′=0M c' = 0, where c′c' stacks c1′,…,cN−1′c_1', \dots, c_{N-1}'. By (G2), the null space is spanned by c′c', so the unit eigenvector of the smallest eigenvalue is ±c′/∥c′∥=±s′c′\pm c' / \|c'\| = \pm s' c' with s′=1/∥c′∥s' = 1 / \|c'\|. Since R0∗R_0^* is a rotation, ∥c′∥2=∑k∥ck∗−c0∗∥2\|c'\|^2 = \sum_k \|c_k^* - c_0^*\|^2, so s′=ss' = s. For the plus sign, ∑vij⋅(cj−ci)=s∑∥cj′−ci′∥>0\sum v_{ij} \cdot (c_j - c_i) = s \sum \|c_j' - c_i'\| > 0, because the two centers of each edge differ by (G1). For the minus sign the sum is negative. So the sign test of line L5 picks c=sc′c = s c', which is the target.

Line L6. It sets tk=−Rkckt_k = -R_k c_k, the target.

Line L7. The cameras are exact, so by (G3) each linear triangulation returns the target point, with all errors 0. All views pass the gate of 10τ10 \tau.

Lines L8 and L9. The cost of the target is 0, so no step can lower it, and each bundle adjustment returns its start unchanged. No error exceeds τ\tau, and each kept point has at least two views, so the filter removes nothing.

So line L10 returns the target. ■\blacksquare

Complexity

In the real RAM model, with a fixed cap on the RANSAC samples, line L1 costs O(Nm)O(N m), because a track seen in dd images belongs to d2/2d^2 / 2 pairs and ∑d2≤Nm\sum d^2 \le N m. Line L2 costs O(E+N3)O(E + N^3) per iteration with the dense solve of the reference code, and it runs a fixed number of iterations. Line L5 needs one symmetric eigenvalue problem of size 3N3N, O(N3)O(N^3) with a dense method. Line L7 costs O(m)O(m). Each bundle adjustment iteration costs O(Nm+N3)O(N m + N^3), as on the incremental page, and the number of iterations is capped. With E≤N2E \le N^2, the total is O(Nm+N3)O(N m + N^3), against O(N2m+N4)O(N^2 m + N^4) for the incremental method, which runs a bundle adjustment after each new image. Sparse solvers make the averaging steps close to linear in EE. The space is O(N2)O(N^2) for the dense matrices plus O(m)O(m) for the data.

Properties

  • Randomized. RANSAC in line L1 samples at random; the reference code fixes the seed.
  • Order free. No step depends on the order of the images, so the errors spread over the whole scene and there is no drift along a sequence.
  • Fast. It has only a few large solves and one or two bundle adjustments (benchmark result in the cited papers).
  • Fragile translations. The quality depends on the translation step, which is sensitive to wrong directions, short baselines and collinear cameras.
  • Fewer images registered. Images that are only weakly connected may be lost by the filters, while the incremental method can still add them by PnP.

Variants and improvements

  • Cycle checks. Moulon, Monasse and Marlet (2013) reject wrong relative rotations with cycles of length 3 before averaging, and estimate translations from triplets of cameras.
  • Robust translations. 1DSfM (Wilson and Snavely, 2014) removes wrong directions by one-dimensional projections, and LUD and ShapeFit use convex robust costs.
  • Points in the translation step. Using the tracks directly, as the constraints x×(RiX+ti)=0x \times (R_i X + t_i) = 0, avoids collinear degeneracies.
  • Joint positioning. GLOMAP (Pan, Baráth, Pollefeys and Schönberger, 2024) replaces the separate translation step by one robust estimation of camera centers and points together, with accuracy close to the incremental method on their benchmarks (benchmark result of the authors).
  • Hybrid methods. Use global rotations with incremental registration of the centers, or merge incremental models with global averaging.

When to use it

Use it for large unordered photo collections when speed matters and the view graph is dense, with many loops. Use it when the images have no natural order and drift is a concern. If the view graph is sparse, close to a chain, or the cameras move along a line, as in a video from a car, the translation step is weak; use incremental structure from motion or visual odometry there.

Pitfalls

  • Wrong edges. Repetitive structures give wrong pairs that agree with each other. Robust losses and cycle checks reduce the risk but cannot remove it.
  • Collinear cameras. If the cameras move along a line, the directions say nothing about the spacing along the line, and the linear step returns a poor answer.
  • Clustering. The linear cost favors short distances, so the minimum can pull groups of cameras together. Use a robust or scale-aware cost, or the points.
  • Disconnected filters. Removing edges can break the graph into parts, and a connected graph can still fail to be parallel rigid. Take the largest parallel rigid part. The reference code only checks connectivity and raises an error if it fails.
  • Sign of the directions. The linear cost does not see the sign of vijv_{ij}, so the solution must be oriented, as line L5 does.

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.

cvgeom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Camera geometry and synthetic scenes for the computer vision pages.

Conventions (prompts of the area, also stated on the pages):
- The camera frame has X to the right, Y down and Z forward. A point is in
  front of the camera if Z > 0.
- K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]] in pixels.
- A world point Xw maps to the camera frame by Xc = R Xw + t. The camera
  matrix is P = K [R | t], and the center is C = -R^T t.
- Rotations are active and right-handed. Quaternions are (w, x, y, z) in the
  Hamilton convention.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

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

from cvla import det, matvec, mul, solve, transpose

Matrix = List[List[float]]
Vector = List[float]


def to_h(x: Sequence[float]) -> Vector:
    """Append a 1: the homogeneous vector of a point."""
    return [float(v) for v in x] + [1.0]


def from_h(x: Sequence[float]) -> Vector:
    """Divide by the last entry and drop it. Raises ValueError if the last
    entry is zero (a point at infinity)."""
    w = x[-1]
    if w == 0:
        raise ValueError("from_h: point at infinity")
    return [v / w for v in x[:-1]]


def make_K(fx: float, fy: float, cx: float, cy: float, s: float = 0.0) -> Matrix:
    """The intrinsic matrix [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
    return [[float(fx), float(s), float(cx)],
            [0.0, float(fy), float(cy)],
            [0.0, 0.0, 1.0]]


def camera_matrix(K: Sequence[Sequence[float]], R: Sequence[Sequence[float]],
                  t: Sequence[float]) -> Matrix:
    """The 3 x 4 camera matrix P = K [R | t]."""
    rt = [list(R[i]) + [t[i]] for i in range(3)]
    return mul(K, rt)


def project(P: Sequence[Sequence[float]], X):
    """Pixel coordinates (u, v) of a point X under the camera P.

    X is a 3D point (3 entries) or a homogeneous point (4 entries). If X is
    a list of points, the result is the list of their projections."""
    if len(X) > 0 and isinstance(X[0], (list, tuple)):
        return [project(P, x) for x in X]
    xh = to_h(X) if len(X) == 3 else list(X)
    return from_h(matvec(P, xh))


def camera_center(P: Sequence[Sequence[float]]) -> Vector:
    """The center C of a finite camera P = [M | p4]: C = -M^-1 p4, so that
    P (C, 1) = 0."""
    m = [list(row[:3]) for row in P]
    p4 = [row[3] for row in P]
    return [-v for v in solve(m, p4)]


def rot_x(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the X axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def axis_angle_to_R(axis: Sequence[float], theta: Optional[float] = None) -> Matrix:
    """Rotation by theta (radians) about the axis, by the right-hand rule
    (Rodrigues formula). The axis need not be a unit vector. If theta is
    None, axis is the rotation vector w = theta a, with theta = ||w||."""
    n = math.sqrt(sum(float(v) * float(v) for v in axis))
    if theta is None:
        theta = n
    if n == 0.0 or theta == 0.0:
        return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    x, y, z = (float(v) / n for v in axis)
    c, s = math.cos(theta), math.sin(theta)
    d = 1.0 - c
    return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
            [y * x * d + z * s, c + y * y * d, y * z * d - x * s],
            [z * x * d - y * s, z * y * d + x * s, c + z * z * d]]


def quat_to_R(q: Sequence[float]) -> Matrix:
    """Rotation matrix of the quaternion q = (w, x, y, z), Hamilton
    convention. q is normalized first; q and -q give the same matrix."""
    n = math.sqrt(sum(float(v) * float(v) for v in q))
    if n == 0.0:
        raise ValueError("quat_to_R: zero quaternion")
    w, x, y, z = (float(v) / n for v in q)
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def random_rotation(rng: random.Random) -> Matrix:
    """A rotation drawn from the uniform (Haar) distribution: a uniform
    random unit quaternion by the method of Shoemake (1992)."""
    u1, u2, u3 = rng.random(), rng.random(), rng.random()
    a, b = math.sqrt(1.0 - u1), math.sqrt(u1)
    q = (b * math.cos(2 * math.pi * u3), a * math.sin(2 * math.pi * u2),
         a * math.cos(2 * math.pi * u2), b * math.sin(2 * math.pi * u3))
    return quat_to_R(q)


def _small_rotation(rng: random.Random, max_angle: float) -> Matrix:
    axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
    return axis_angle_to_R(axis, rng.uniform(0.0, max_angle))


def random_scene(rng: random.Random, n: int = 20, n_cams: int = 2,
                 K: Optional[Sequence[Sequence[float]]] = None,
                 cams: Optional[Sequence[Tuple]] = None,
                 radius: float = 1.0, distance: float = 5.0,
                 max_angle: float = 0.3, planar: bool = False,
                 first_identity: bool = False,
                 size: Optional[Tuple[float, float]] = None,
                 min_depth: float = 0.1) -> Dict[str, list]:
    """A synthetic scene with known cameras and points.

    Cameras: if cams is given, it is a list of (K, R, t) and is used as it
    is. Otherwise n_cams cameras look at the world origin from the distance
    `distance`. Each one is the camera at center (0, 0, -distance) with
    R = I, turned about the origin by a random rotation of angle at most
    max_angle (radians). K defaults to make_K(800, 800, 320, 240). With
    first_identity, the world frame is moved to the frame of camera 0, so
    that camera 0 has R = I and t = 0 (the points move with it).

    Points: n points drawn uniformly in the cube [-radius, radius]^3 (with
    Z = 0 if planar, before any move of the world frame). A point is kept
    only if its depth is at least min_depth in every camera, and, if size =
    (W, H) is given, if its projection lies in [0, W] x [0, H] in every
    camera. Raises ValueError if 1000 n draws are not enough.

    Returns a dict with lists "K", "R", "t", "P" (one entry per camera),
    "X" (the 3D points) and "x" (x[i][j] is the pixel of point j in
    camera i, without noise)."""
    if cams is not None:
        Ks = [[list(r) for r in c[0]] for c in cams]
        Rs = [[list(r) for r in c[1]] for c in cams]
        ts = [list(c[2]) for c in cams]
    else:
        k0 = [list(r) for r in K] if K is not None else make_K(800, 800, 320, 240)
        Ks, Rs, ts = [], [], []
        c0 = [0.0, 0.0, -float(distance)]
        for _ in range(n_cams):
            q = _small_rotation(rng, max_angle)
            r = transpose(q)
            center = matvec(q, c0)
            Ks.append([list(row) for row in k0])
            Rs.append(r)
            ts.append([-v for v in matvec(r, center)])
    pts: List[Vector] = []
    tries = 0
    while len(pts) < n:
        tries += 1
        if tries > 1000 * max(n, 1):
            raise ValueError("random_scene: cannot place the points")
        x = [rng.uniform(-radius, radius) for _ in range(3)]
        if planar:
            x[2] = 0.0
        ok = True
        for k, r, t in zip(Ks, Rs, ts):
            xc = [a + b for a, b in zip(matvec(r, x), t)]
            if xc[2] < min_depth:
                ok = False
                break
            if size is not None:
                u = (k[0][0] * xc[0] + k[0][1] * xc[1]) / xc[2] + k[0][2]
                v = k[1][1] * xc[1] / xc[2] + k[1][2]
                if not (0.0 <= u <= size[0] and 0.0 <= v <= size[1]):
                    ok = False
                    break
        if ok:
            pts.append(x)
    if first_identity and Rs:
        r0, t0 = Rs[0], ts[0]
        pts = [[a + b for a, b in zip(matvec(r0, x), t0)] for x in pts]
        r0t = transpose(r0)
        newR, newt = [], []
        for r, t in zip(Rs, ts):
            rr = mul(r, r0t)
            newR.append(rr)
            newt.append([a - b for a, b in zip(t, matvec(rr, t0))])
        Rs, ts = newR, newt
        Rs[0] = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
        ts[0] = [0.0, 0.0, 0.0]
    Ps = [camera_matrix(k, r, t) for k, r, t in zip(Ks, Rs, ts)]
    xs = [[project(p, x) for x in pts] for p in Ps]
    return {"K": Ks, "R": Rs, "t": ts, "P": Ps, "X": pts, "x": xs}


def add_noise(rng: random.Random, pts: Sequence[Sequence[float]], sigma: float) -> List[Vector]:
    """A copy of the points with independent Gaussian noise of standard
    deviation sigma added to every coordinate."""
    return [[float(v) + rng.gauss(0.0, sigma) for v in p] for p in pts]


def self_test() -> None:
    """Check random_scene and quat_to_R. Raises AssertionError."""
    rng = random.Random(11)
    scene = random_scene(rng, n=30, n_cams=4)
    for r, t in zip(scene["R"], scene["t"]):
        for x in scene["X"]:
            assert matvec(r, x)[2] + t[2] > 0.0
    for _ in range(5):
        q = [rng.gauss(0.0, 1.0) for _ in range(4)]
        r = quat_to_R(q)
        rtr = mul(transpose(r), r)
        assert all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) <= 1e-12
                   for i in range(3) for j in range(3))
        assert abs(det(r) - 1.0) <= 1e-12


if __name__ == "__main__":
    self_test()
cvla.py 494 lines
# 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()
global_structure_from_motion.py 494 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/global-structure-from-motion/. The authors are listed in prov/JSXC11.jsonl.

"""Global structure from motion with a known intrinsic matrix K.

The input is K and a list of tracks. A track is a dict {image: (u, v)}
of the pixels of one 3D point. The output is a pose (R, t) for every
image of the largest connected part of the view graph, with
X_c = R X + t, and a 3D point for every track that could be
triangulated. The first image of that part has R = I and t = 0; the
scale is arbitrary.

The pipeline solves for all cameras at once instead of one by one:
1. relative poses of all image pairs with enough common tracks (RANSAC
   on the 8-point method), which give the view graph;
2. robust rotation averaging in the Lie algebra (an l1 start, then
   Geman-McClure weights);
3. removal of the edges that disagree with the averaged rotations;
4. unit directions between the camera centers, from the relative
   translations and the averaged rotations;
5. linear translation averaging: the centers that best fit the
   directions, as the smallest eigenvector of a block Laplacian;
6. triangulation of all tracks, then one bundle adjustment and the
   removal of observations with a reprojection error above tau.
"""

import math
import random
from collections import deque
from typing import Dict, List, Sequence, Tuple

from cvgeom import axis_angle_to_R
from cvla import det, dot, inv, matvec, mul, nullvec, solve, svd, sym_eig, transpose

Vector = List[float]
Matrix = List[List[float]]
Pose = Tuple[Matrix, Vector]
Edge = Tuple[int, int, Matrix]
EYE3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]


# ------------------------------------------------------------ two-view geometry

def normalize(kinv: Matrix, p: Sequence[float]) -> Vector:
    """The normalized image point (x, y) of the pixel p: K^-1 (u, v, 1)."""
    q = matvec(kinv, [p[0], p[1], 1.0])
    return [q[0] / q[2], q[1] / q[2]]


def to_cam(pose: Pose, x: Sequence[float]) -> Vector:
    r, t = pose
    return [dot(r[a], x) + t[a] for a in range(3)]


def reproj_error(pose: Pose, x: Sequence[float], p: Sequence[float]) -> float:
    """Distance in normalized coordinates; infinite behind the camera."""
    c = to_cam(pose, x)
    if c[2] <= 0:
        return math.inf
    return math.hypot(c[0] / c[2] - p[0], c[1] / c[2] - p[1])


def triangulate(poses: Sequence[Pose], pts: Sequence[Sequence[float]]) -> Vector:
    """Linear (DLT) triangulation from two or more normalized points."""
    rows = []
    for (r, t), (x, y) in zip(poses, pts):
        p = [r[a] + [t[a]] for a in range(3)]
        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-12:
        return [math.inf] * 3
    return [h[k] / h[3] for k in range(3)]


def _conditioner(pts: Sequence[Vector]) -> Matrix:
    n = len(pts)
    cx, cy = sum(p[0] for p in pts) / n, sum(p[1] for p in pts) / n
    d = sum(math.hypot(p[0] - cx, p[1] - cy) for p in pts) / n or 1.0
    s = math.sqrt(2.0) / d
    return [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]]


def eight_point_essential(x1: Sequence[Vector], x2: Sequence[Vector]) -> Matrix:
    """E with x2^T E x1 = 0, projected to singular values (1, 1, 0)."""
    t1, t2 = _conditioner(x1), _conditioner(x2)
    y1 = [matvec(t1, [p[0], p[1], 1.0]) for p in x1]
    y2 = [matvec(t2, [q[0], q[1], 1.0]) for q in x2]
    a = [[q[0] * p[0], q[0] * p[1], q[0], q[1] * p[0], q[1] * p[1], q[1], p[0], p[1], 1.0]
         for p, q in zip(y1, y2)]
    e = nullvec(a)
    e = mul(mul(transpose(t2), [e[0:3], e[3:6], e[6:9]]), t1)
    u, _, v = svd(e)
    return mul(mul(u, [[1.0, 0, 0], [0, 1.0, 0], [0, 0, 0.0]]), transpose(v))


def sampson(e: Matrix, p: Sequence[float], q: Sequence[float]) -> float:
    x1, x2 = [p[0], p[1], 1.0], [q[0], q[1], 1.0]
    ex1 = matvec(e, x1)
    etx2 = matvec(transpose(e), x2)
    num = dot(x2, ex1)
    den = ex1[0] ** 2 + ex1[1] ** 2 + etx2[0] ** 2 + etx2[1] ** 2
    return math.sqrt(num * num / den) if den > 0 else math.inf


def decompose_essential(e: Matrix, x1: Sequence[Vector], x2: Sequence[Vector]) -> Pose:
    """The (R, t) among the four candidates that puts the most points in
    front of both cameras; ||t|| = 1."""
    u, _, v = svd(e)
    if det(u) < 0:
        u = [[-c for c in row] for row in u]
    if det(v) < 0:
        v = [[-c for c in row] for row in v]
    w = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
    u3 = [u[a][2] for a in range(3)]
    best, best_count = None, -1
    for r in (mul(mul(u, w), transpose(v)), mul(mul(u, transpose(w)), transpose(v))):
        for t in (u3, [-c for c in u3]):
            count = 0
            for p, q in zip(x1, x2):
                x = triangulate([(EYE3, [0.0, 0.0, 0.0]), (r, t)], [p, q])
                if x[2] > 0 and to_cam((r, t), x)[2] > 0:
                    count += 1
            if count > best_count:
                best, best_count = (r, list(t)), count
    return best


def ransac_count(inlier_ratio: float, sample: int, cap: int) -> int:
    if inlier_ratio <= 0:
        return cap
    w = inlier_ratio ** sample
    if w >= 1:
        return 1
    return min(cap, int(math.ceil(math.log(0.01) / math.log(1 - w))))


def relative_pose_ransac(x1: Sequence[Vector], x2: Sequence[Vector], tau: float,
                         rng: random.Random, cap: int = 300) -> Tuple[Pose, List[int]]:
    """RANSAC on the 8-point method with a local refit: each new best model
    is fitted again to its inliers. Returns the pose and the inlier indices."""
    n = len(x1)
    best: List[int] = []
    best_e = None
    it, need = 0, cap
    while it < need:
        it += 1
        s = rng.sample(range(n), 8)
        e = eight_point_essential([x1[k] for k in s], [x2[k] for k in s])
        inl = [k for k in range(n) if sampson(e, x1[k], x2[k]) < tau]
        if len(inl) > len(best):
            for _ in range(3):
                e2 = eight_point_essential([x1[k] for k in inl], [x2[k] for k in inl])
                inl2 = [k for k in range(n) if sampson(e2, x1[k], x2[k]) < tau]
                if len(inl2) < len(inl):
                    break
                e, inl = e2, inl2
            if len(inl) > len(best):
                best, best_e = inl, e
                need = ransac_count(len(best) / n, 8, cap)
    pose = decompose_essential(best_e, [x1[k] for k in best], [x2[k] for k in best])
    return pose, best


# ------------------------------------------------------------ rotation averaging

def so3_exp(w: Sequence[float]) -> Matrix:
    """exp([w]_x) by the Rodrigues formula."""
    th = math.sqrt(w[0] * w[0] + w[1] * w[1] + w[2] * w[2])
    if th < 1e-8:
        a, b = 1.0 - th * th / 6.0, 0.5 - th * th / 24.0
    else:
        a, b = math.sin(th) / th, (1.0 - math.cos(th)) / (th * th)
    x, y, z = w
    k = [[0.0, -z, y], [z, 0.0, -x], [-y, x, 0.0]]
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r: Sequence[Sequence[float]]) -> Vector:
    """The rotation vector w with exp([w]_x) = R and ||w|| <= pi."""
    c = max(-1.0, min(1.0, (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0))
    v = [r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]]
    th = math.acos(c)
    if th < 1e-6:
        return [x * (0.5 + th * th / 12.0) for x in v]
    if th < math.pi - 1e-4:
        return [x * th / (2.0 * math.sin(th)) for x in v]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    nc = math.sqrt(sum(x * x for x in col))
    a = [x / nc for x in col]
    if sum(x * y for x, y in zip(a, v)) < 0:
        a = [-x for x in a]
    return [th * x for x in a]


def angle(r1: Sequence[Sequence[float]], r2: Sequence[Sequence[float]]) -> float:
    """The angle of R1^T R2, in radians."""
    tr = sum(r1[k][i] * r2[k][i] for i in range(3) for k in range(3))
    return math.acos(max(-1.0, min(1.0, (tr - 1.0) / 2.0)))


def _tree_init(n: int, edges: Sequence[Edge]) -> List[Matrix]:
    adj: Dict[int, List[Tuple[int, Matrix]]] = {k: [] for k in range(n)}
    for i, j, rij in edges:
        adj[i].append((j, rij))
        adj[j].append((i, transpose(rij)))
    rots: List = [None] * n
    rots[0] = [list(row) for row in EYE3]
    queue = deque([0])
    while queue:
        i = queue.popleft()
        for j, rij in adj[i]:
            if rots[j] is None:
                rots[j] = mul(rij, rots[i])
                queue.append(j)
    if any(r is None for r in rots):
        raise ValueError("rotation averaging: the view graph is not connected")
    return rots


def _irls_rotations(n: int, edges: Sequence[Edge], rots: List[Matrix], loss: str,
                    sigma: float, iters: int) -> List[Matrix]:
    """Lie-algebraic iterations with the weights of the loss ("l1" or "gm")."""
    for _ in range(iters):
        lap = [[0.0] * n for _ in range(n)]
        b = [[0.0] * 3 for _ in range(n)]
        for i, j, rij in edges:
            r = so3_log(mul(mul(transpose(rots[j]), rij), rots[i]))
            rn = math.sqrt(dot(r, r))
            w = 1.0 / max(rn, 1e-6) if loss == "l1" else sigma * sigma / (rn * rn + sigma * sigma) ** 2
            lap[i][i] += w
            lap[j][j] += w
            lap[i][j] -= w
            lap[j][i] -= w
            for a in range(3):
                b[j][a] += w * r[a]
                b[i][a] -= w * r[a]
        omega = [[0.0, 0.0, 0.0]] + solve([row[1:] for row in lap[1:]], b[1:])
        rots = [mul(r, so3_exp(w)) for r, w in zip(rots, omega)]
        if max(math.sqrt(dot(w, w)) for w in omega) < 1e-10:
            break
    return rots


def average_rotations(n: int, edges: Sequence[Edge], sigma: float = 0.1) -> List[Matrix]:
    """Robust rotation averaging: tree start, l1 iterations, then
    Geman-McClure iterations. R_0 = I."""
    rots = _tree_init(n, edges)
    rots = _irls_rotations(n, edges, rots, "l1", sigma, 30)
    return _irls_rotations(n, edges, rots, "gm", sigma, 30)


# ------------------------------------------------------------ translation averaging

def directions(rots: Sequence[Matrix], rel: Dict[Tuple[int, int], Pose]) -> Dict[Tuple[int, int], Vector]:
    """v_ij = -R_j^T t_ij / ||t_ij||, the unit vector from c_i to c_j."""
    out = {}
    for (i, j), (_, t) in rel.items():
        d = [-x for x in matvec(transpose(rots[j]), t)]
        nd = math.sqrt(dot(d, d))
        out[(i, j)] = [x / nd for x in d]
    return out


def direction_matrix(n: int, dirs: Dict[Tuple[int, int], Vector]) -> Matrix:
    """The 3(n-1) x 3(n-1) matrix of sum ||(I - v v^T)(c_j - c_i)||^2 with
    c_0 = 0 removed."""
    m = [[0.0] * (3 * n) for _ in range(3 * n)]
    for (i, j), v in dirs.items():
        p = [[(1.0 if a == b else 0.0) - v[a] * v[b] for b in range(3)] for a in range(3)]
        for a in range(3):
            for b in range(3):
                m[3 * i + a][3 * i + b] += p[a][b]
                m[3 * j + a][3 * j + b] += p[a][b]
                m[3 * i + a][3 * j + b] -= p[a][b]
                m[3 * j + a][3 * i + b] -= p[a][b]
    return [row[3:] for row in m[3:]]


def translation_averaging(n: int, dirs: Dict[Tuple[int, int], Vector]) -> List[Vector]:
    """Centers c_i with c_0 = 0 and sum ||c_i||^2 = 1 that minimize the
    sum of ||(I - v_ij v_ij^T)(c_j - c_i)||^2, with the sign that makes
    the directions point the right way."""
    _, vecs = sym_eig(direction_matrix(n, dirs))
    x = [row[0] for row in vecs]
    cs = [[0.0, 0.0, 0.0]] + [x[3 * k:3 * k + 3] for k in range(n - 1)]
    s = sum(dot(v, [cs[j][a] - cs[i][a] for a in range(3)]) for (i, j), v in dirs.items())
    if s < 0:
        cs = [[-a for a in c] for c in cs]
    return cs


# ------------------------------------------------------------ bundle adjustment

def _blocks(pose: Pose, x: Sequence[float], p: Sequence[float]):
    r, t = pose
    rx = matvec(r, x)
    c = [rx[a] + t[a] for a in range(3)]
    iz = 1.0 / c[2]
    res = [c[0] * iz - p[0], c[1] * iz - p[1]]
    d = [[iz, 0.0, -c[0] * iz * iz], [0.0, iz, -c[1] * iz * iz]]
    sk = [[0.0, rx[2], -rx[1]], [-rx[2], 0.0, rx[0]], [rx[1], -rx[0], 0.0]]
    a = [[sum(d[i][k] * sk[k][j] for k in range(3)) for j in range(3)] + d[i] for i in range(2)]
    b = [[sum(d[i][k] * r[k][j] for k in range(3)) for j in range(3)] for i in range(2)]
    return res, a, b


def ba_cost(cams: Dict[int, Pose], pts: Dict[int, Vector], obs: Dict[Tuple[int, int], Vector]) -> float:
    total = 0.0
    for (i, j), p in obs.items():
        c = to_cam(cams[i], pts[j])
        if c[2] <= 0:
            return math.inf
        total += (c[0] / c[2] - p[0]) ** 2 + (c[1] / c[2] - p[1]) ** 2
    return 0.5 * total


def bundle_adjust(cams: Dict[int, Pose], pts: Dict[int, Vector],
                  obs: Dict[Tuple[int, int], Vector], fixed: int,
                  max_iter: int = 20) -> Tuple[Dict[int, Pose], Dict[int, Vector]]:
    """Levenberg-Marquardt on the normalized reprojection error, with the
    points eliminated by the Schur complement. Camera `fixed` is held."""
    free = sorted(i for i in cams if i != fixed)
    col = {i: 6 * k for k, i in enumerate(free)}
    f = ba_cost(cams, pts, obs)
    mu = 1e-3
    for _ in range(max_iter):
        nf = 6 * len(free)
        u = [[0.0] * nf for _ in range(nf)]
        ga = [0.0] * nf
        v: Dict[int, Matrix] = {j: [[0.0] * 3 for _ in range(3)] for j in pts}
        gb: Dict[int, Vector] = {j: [0.0] * 3 for j in pts}
        wb: Dict[int, Dict[int, Matrix]] = {j: {} for j in pts}
        for (i, j), p in obs.items():
            res, a, b = _blocks(cams[i], pts[j], p)
            for r in range(3):
                for s in range(3):
                    v[j][r][s] += b[0][r] * b[0][s] + b[1][r] * b[1][s]
                gb[j][r] += b[0][r] * res[0] + b[1][r] * res[1]
            if i in col:
                o = col[i]
                for r in range(6):
                    for s in range(6):
                        u[o + r][o + s] += a[0][r] * a[0][s] + a[1][r] * a[1][s]
                    ga[o + r] += a[0][r] * res[0] + a[1][r] * res[1]
                wb[j][i] = [[a[0][r] * b[0][s] + a[1][r] * b[1][s] for s in range(3)] for r in range(6)]
        while True:
            vinv = {j: inv([[v[j][r][s] + (mu if r == s else 0.0) for s in range(3)] for r in range(3)])
                    for j in pts}
            sm = [[u[r][s] + (mu if r == s else 0.0) for s in range(nf)] for r in range(nf)]
            rhs = [-g for g in ga]
            for j in pts:
                wv = {i: mul(wj, vinv[j]) for i, wj in wb[j].items()}
                vg = matvec(vinv[j], gb[j])
                for i, wvi in wv.items():
                    oi = col[i]
                    for r in range(6):
                        rhs[oi + r] += dot(wb[j][i][r], vg)
                    for k, wk in wb[j].items():
                        ok = col[k]
                        for r in range(6):
                            for s in range(6):
                                sm[oi + r][ok + s] -= dot(wvi[r], wk[s])
            da = solve(sm, rhs) if nf else []
            new_cams = dict(cams)
            for i in free:
                d = da[col[i]:col[i] + 6]
                r, t = cams[i]
                new_cams[i] = (mul(axis_angle_to_R(d[0:3]), r), [t[a] + d[3 + a] for a in range(3)])
            new_pts = {}
            for j in pts:
                g = list(gb[j])
                for i, wj in wb[j].items():
                    d = da[col[i]:col[i] + 6]
                    g = [g[r] + sum(wj[k][r] * d[k] for k in range(6)) for r in range(3)]
                db = matvec(vinv[j], [-x for x in g])
                new_pts[j] = [pts[j][a] + db[a] for a in range(3)]
            f_new = ba_cost(new_cams, new_pts, obs)
            if f_new < f:
                done = f - f_new < 1e-12 * f + 1e-30
                cams, pts, f = new_cams, new_pts, f_new
                mu = max(mu / 3.0, 1e-12)
                break
            mu *= 4.0
            if mu > 1e12:
                return cams, pts
        if done:
            break
    return cams, pts


# ------------------------------------------------------------ pipeline

def build_view_graph(xn: Sequence[Dict[int, Vector]], tau: float, rng: random.Random,
                     min_pair: int = 12) -> Dict[Tuple[int, int], Tuple[Pose, int]]:
    """Relative pose and inlier count of every image pair (i < j) with at
    least min_pair common tracks and min_pair inliers."""
    common: Dict[Tuple[int, int], List[int]] = {}
    for j, tr in enumerate(xn):
        ims = sorted(tr)
        for x in range(len(ims)):
            for y in range(x + 1, len(ims)):
                common.setdefault((ims[x], ims[y]), []).append(j)
    graph = {}
    for (a, b) in sorted(common):
        js = common[(a, b)]
        if len(js) < min_pair:
            continue
        pose, inl = relative_pose_ransac([xn[j][a] for j in js], [xn[j][b] for j in js], tau, rng)
        if len(inl) >= min_pair:
            graph[(a, b)] = (pose, len(inl))
    return graph


def largest_component(images: Sequence[int], pairs) -> List[int]:
    adj: Dict[int, List[int]] = {i: [] for i in images}
    for a, b in pairs:
        adj[a].append(b)
        adj[b].append(a)
    seen, best = set(), []
    for s in sorted(images):
        if s in seen:
            continue
        comp, queue = [], deque([s])
        seen.add(s)
        while queue:
            i = queue.popleft()
            comp.append(i)
            for k in adj[i]:
                if k not in seen:
                    seen.add(k)
                    queue.append(k)
        if len(comp) > len(best):
            best = sorted(comp)
    return best


def filter_edges(rots: Sequence[Matrix], rel: Dict[Tuple[int, int], Pose],
                 max_angle: float) -> Dict[Tuple[int, int], Pose]:
    """Keep the edges with angle(R_ij, R_j R_i^T) <= max_angle."""
    return {(i, j): (r, t) for (i, j), (r, t) in rel.items()
            if angle(r, mul(rots[j], transpose(rots[i]))) <= max_angle}


def global_structure_from_motion(K: Matrix, tracks: Sequence[Dict[int, Sequence[float]]],
                                 tau_px: float = 3.0, max_angle: float = 0.1,
                                 min_pair: int = 12, seed: int = 0):
    """Returns (cams, pts, obs): cams[i] = (R, t), pts[j] = X for track j,
    and obs, the set of (image, track) pairs that were kept."""
    rng = random.Random(seed)
    kinv = inv(K)
    tau = tau_px / K[0][0]
    xn = [{i: normalize(kinv, p) for i, p in tr.items()} for tr in tracks]
    graph = build_view_graph(xn, tau, rng, min_pair)  # @line L1
    images = largest_component(sorted({i for tr in tracks for i in tr}), graph)
    idx = {im: k for k, im in enumerate(images)}
    n = len(images)
    rel = {(idx[a], idx[b]): pose for (a, b), (pose, _) in graph.items() if a in idx and b in idx}
    rots = average_rotations(n, [(i, j, r) for (i, j), (r, _) in rel.items()])  # @line L2
    rel = filter_edges(rots, rel, max_angle)  # @line L3
    if len(largest_component(range(n), rel)) < n:
        raise ValueError("global SfM: the filtered view graph is not connected")
    dirs = directions(rots, rel)  # @line L4
    centers = translation_averaging(n, dirs)  # @line L5
    cams: Dict[int, Pose] = {images[k]: (rots[k], [-x for x in matvec(rots[k], centers[k])])
                             for k in range(n)}  # @line L6
    pts: Dict[int, Vector] = {}
    obs: Dict[Tuple[int, int], Vector] = {}
    for j, tr in enumerate(xn):  # @line L7
        views = [i for i in tr if i in cams]
        if len(views) < 2:
            continue
        x = triangulate([cams[i] for i in views], [tr[i] for i in views])
        good = [i for i in views if reproj_error(cams[i], x, tr[i]) < 10 * tau]
        if 2 <= len(good) < len(views):
            x = triangulate([cams[i] for i in good], [tr[i] for i in good])
            good = [i for i in good if reproj_error(cams[i], x, tr[i]) < 10 * tau]
        if len(good) >= 2:
            pts[j] = x
            for i in good:
                obs[(i, j)] = tr[i]
    cams, pts = bundle_adjust(cams, pts, obs, images[0])  # @line L8
    for key in [k for k in obs if reproj_error(cams[k[0]], pts[k[1]], obs[k]) > tau]:  # @line L9
        del obs[key]
    for j in list(pts):
        if sum(1 for (_, jj) in obs if jj == j) < 2:
            del pts[j]
            for key in [k for k in obs if k[1] == j]:
                del obs[key]
    cams, pts = bundle_adjust(cams, pts, obs, images[0])
    return cams, pts, set(obs)  # @line L10
test_global_structure_from_motion.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/global-structure-from-motion/. The authors are listed in prov/JSXC11.jsonl.

import math
import random

from cvgeom import axis_angle_to_R, make_K, random_scene, rot_x, rot_y
from cvla import det, inv, matvec, mul, svd, sym_eig, transpose
from global_structure_from_motion import (angle, average_rotations, direction_matrix, directions,
                                          filter_edges, global_structure_from_motion, normalize,
                                          reproj_error, translation_averaging)


def ring_cameras():
    """Five cameras on a sphere of radius 3 around the origin, looking at it."""
    k = make_K(800, 800, 320, 240)
    cams = []
    for a, b in [(-0.4, 0.0), (-0.2, 0.25), (0.0, -0.25), (0.2, 0.25), (0.4, 0.0)]:
        q = mul(rot_y(a), rot_x(b))
        r = transpose(q)
        c = matvec(q, [0.0, 0.0, -3.0])
        cams.append((k, r, [-x for x in matvec(r, c)]))
    return cams


def make_tracks(seed, n_pts=40, visible=0.8, noise=0.0, outliers=0.0):
    rng = random.Random(seed)
    sc = random_scene(rng, n=n_pts, cams=ring_cameras())
    n_cams = 5
    tracks = []
    for j in range(n_pts):
        views = [i for i in range(n_cams) if rng.random() < visible]
        if len(views) < 2:
            views = rng.sample(range(n_cams), 2)
        tr = {}
        for i in views:
            u, v = sc["x"][i][j]
            if rng.random() < outliers:
                u, v = rng.uniform(0, 640), rng.uniform(0, 480)
            else:
                u, v = u + rng.gauss(0, noise), v + rng.gauss(0, noise)
            tr[i] = (u, v)
        tracks.append(tr)
    return sc, tracks


def umeyama(src, dst):
    """s, R, t minimizing sum ||s R src + t - dst||^2."""
    n = len(src)
    ms = [sum(p[a] for p in src) / n for a in range(3)]
    md = [sum(p[a] for p in dst) / n for a in range(3)]
    cov = [[sum((d[a] - md[a]) * (s[b] - ms[b]) for s, d in zip(src, dst)) / n for b in range(3)]
           for a in range(3)]
    u, sv, v = svd(cov)
    sgn = [1.0, 1.0, 1.0 if det(mul(u, transpose(v))) > 0 else -1.0]
    r = mul(mul(u, [[sgn[0], 0, 0], [0, sgn[1], 0], [0, 0, sgn[2]]]), transpose(v))
    var = sum(sum((p[a] - ms[a]) ** 2 for a in range(3)) for p in src) / n
    s = sum(x * g for x, g in zip(sv, sgn)) / var
    t = [md[a] - s * sum(r[a][b] * ms[b] for b in range(3)) for a in range(3)]
    return s, r, t


def aligned_error(src, dst):
    s, r, t = umeyama(src, dst)
    return max(math.dist([s * x + t[a] for a, x in enumerate(matvec(r, p))], q) for p, q in zip(src, dst))


def center(pose):
    r, t = pose
    return [-x for x in matvec(transpose(r), t)]


def exact_relative(sc, pairs):
    rel = {}
    for i, j in pairs:
        rij = mul(sc["R"][j], transpose(sc["R"][i]))
        tij = [sc["t"][j][a] - sum(rij[a][b] * sc["t"][i][b] for b in range(3)) for a in range(3)]
        n = math.sqrt(sum(x * x for x in tij))
        rel[(i, j)] = (rij, [x / n for x in tij])
    return rel


def test_exact_tracks_give_the_true_scene_up_to_similarity():
    sc, tracks = make_tracks(1)
    cams, pts, obs = global_structure_from_motion(sc["K"][0], tracks)
    assert sorted(cams) == list(range(5))
    assert len(pts) == 40
    js = sorted(pts)
    assert aligned_error([pts[j] for j in js], [sc["X"][j] for j in js]) < 1e-6
    assert cams[0][0] == [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]


def test_noise_and_outliers():
    sc, tracks = make_tracks(2, noise=0.5, outliers=0.05)
    cams, pts, obs = global_structure_from_motion(sc["K"][0], tracks)
    assert sorted(cams) == list(range(5))
    assert len(pts) >= 34
    f = sc["K"][0][0][0]
    kinv = inv(sc["K"][0])
    errs = [reproj_error(cams[i], pts[j], normalize(kinv, tracks[j][i])) * f for i, j in obs]
    assert max(errs) < 3.0
    assert math.sqrt(sum(e * e for e in errs) / len(errs)) < 1.0
    js = sorted(pts)
    assert aligned_error([pts[j] for j in js], [sc["X"][j] for j in js]) < 0.05
    assert aligned_error([center(cams[i]) for i in range(5)],
                         [center((sc["R"][i], sc["t"][i])) for i in range(5)]) < 0.1


def test_the_edge_filter_removes_a_wrong_relative_rotation():
    sc = random_scene(random.Random(3), n=4, n_cams=6, max_angle=0.6)
    pairs = [(i, j) for i in range(6) for j in range(i + 1, 6)]
    rel = exact_relative(sc, pairs)
    r, t = rel[(1, 4)]
    rel[(1, 4)] = (mul(axis_angle_to_R([1.0, 2.0, 0.5], 0.5), r), t)
    rots = average_rotations(6, [(i, j, r) for (i, j), (r, _) in rel.items()])
    for k in range(6):
        # R_k = R_k^true R_0^true^T, since R_0 = I. The Geman-McClure cost
        # keeps a small pull from the wrong edge, so the match is not exact.
        assert angle(rots[k], mul(sc["R"][k], transpose(sc["R"][0]))) < 2e-3
    kept = filter_edges(rots, rel, 0.1)
    assert sorted(kept) == [p for p in pairs if p != (1, 4)]


def test_translation_averaging_on_exact_directions():
    sc = random_scene(random.Random(4), n=4, n_cams=6, max_angle=0.8)
    rots = [mul(r, transpose(sc["R"][0])) for r in sc["R"]]
    pairs = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (0, 5), (0, 2), (1, 3), (2, 4), (3, 5)]
    rel = exact_relative(sc, pairs)
    cs = translation_averaging(6, directions(rots, rel))
    true = [matvec(sc["R"][0], [a - b for a, b in zip(center((sc["R"][k], sc["t"][k])),
                                                        center((sc["R"][0], sc["t"][0])))])
            for k in range(6)]
    s = math.sqrt(sum(x * x for c in true for x in c))
    assert max(abs(a - b / s) for c, d in zip(cs, true) for a, b in zip(c, d)) < 1e-9


def test_a_tree_of_directions_does_not_fix_the_centers():
    sc = random_scene(random.Random(5), n=4, n_cams=4, max_angle=0.8)
    rots = [mul(r, transpose(sc["R"][0])) for r in sc["R"]]
    chain = directions(rots, exact_relative(sc, [(0, 1), (1, 2), (2, 3)]))
    w, _ = sym_eig(direction_matrix(4, chain))
    assert sum(1 for x in w if abs(x) < 1e-9) == 3
    full = directions(rots, exact_relative(sc, [(0, 1), (1, 2), (2, 3), (0, 3)]))
    w, _ = sym_eig(direction_matrix(4, full))
    assert sum(1 for x in w if abs(x) < 1e-9) == 1

History

Govindu (2001) proposed to combine the relative motions of all image pairs into consistent global motions by averaging, first the rotations and then the translations. Martinec and Pajdla (2007) built a full pipeline with linear rotation averaging and a robust translation step on all cameras. Around 2013 and 2014, robust rotation averaging (Chatterjee and Govindu), the global fusion of relative motions (Moulon, Monasse and Marlet) and robust translations by 1DSfM (Wilson and Snavely) made global SfM competitive on large Internet collections. The Acta Numerica survey of Özyeşil, Voroninski, Basri and Singer (2017) reviews the theory. GLOMAP (Pan, Baráth, Pollefeys and Schönberger, 2024) closed much of the accuracy gap with the incremental method.

References

  1. Venu Madhav Govindu, Combining two-view constraints for motion estimation, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2001), vol. 2, 218-225, the whole paper (the global estimation of all rotations and translations from the pairwise motions)
  2. Daniel Martinec and Tomas Pajdla, Robust rotation and translation estimation in multiview reconstruction, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2007), 1-8, the whole paper (the linear rotation step and the translation step on all cameras at once)
  3. Pierre Moulon, Pascal Monasse and Renaud Marlet, Global fusion of relative motions for robust, accurate and scalable structure from motion, IEEE International Conference on Computer Vision (ICCV 2013), 3248-3255, the whole paper (the rejection of wrong rotations by cycles, robust rotation averaging and the translation step on triplets)
  4. Kyle Wilson and Noah Snavely, Robust global translations with 1DSfM, Computer Vision ECCV 2014, Lecture Notes in Computer Science, Springer, 2014, 61-75, the whole paper (the outlier filter for the directions and the translation step of a global pipeline)
  5. Avishek Chatterjee and Venu Madhav Govindu, Efficient and robust large-scale rotation averaging, IEEE International Conference on Computer Vision (ICCV 2013), 521-528, the robust rotation averaging used as the first step
  6. Linfei Pan, Dániel Baráth, Marc Pollefeys and Johannes L. Schönberger, Global structure-from-motion revisited, Computer Vision ECCV 2024, Lecture Notes in Computer Science, Springer, 2024, 58-77, the whole paper (the joint estimation of cameras and points in place of a separate translation step)
  7. Onur Özyeşil, Vladislav Voroninski, Ronen Basri and Amit Singer, A survey of structure from motion, Acta Numerica 26, 2017, 305-364, the sections on the global pipeline, rotation estimation and location estimation

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.total
  • 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