Algorithm Search⌘K

Algorithmcore

Incremental structure from motion

Also called sequential structure from motion.

Start from a good image pair, then add one image at a time by PnP, triangulate its new points and bundle adjust, rejecting outliers as it goes.

Time
O(N^2 m + N^4) total
Space
O(N^2 + m) extra
Where
N = the number of images; m = the number of observations; n = the number of tracks
Properties
randomizediterativelocalnot monotoneiterative
Origin
Noah Snavely, Steven M. Seitz, Richard Szeliski, Johannes L. Schönberger, Jan Michael Frahm, 2006

Incremental structure from motion is the most used way to solve the structure from motion problem for calibrated cameras. It builds the reconstruction one image at a time. It starts from one image pair with many matches, finds the relative pose of the pair from the essential matrix, and triangulates the common tracks. Then it repeats three steps: it picks the next image that sees many points that are already in 3D, finds its pose by PnP inside RANSAC, triangulates the tracks that the new image makes visible in two images, and runs bundle adjustment to refine all cameras and points together. After each bundle adjustment it drops the observations with a large reprojection error. Each step is a small, well understood problem with a robust solver, and the repeated bundle adjustment stops the errors from piling up, which makes the method accurate and reliable. The cost is that the bundle adjustments become expensive for many images, and a bad early decision can spoil the rest.

In plain words

Think of a jigsaw puzzle that you build from one corner. First you find two photos that overlap a lot and work out how the second camera stood compared with the first. From these two views you place the first set of points in 3D. Next you look for the photo that sees the most of the points you have already placed. From those points you can work out where that camera stood. Now the new photo lets you place more points. Then you adjust everything a little, so that all the points and cameras agree as well as possible, and you throw away the matches that still do not fit. You repeat this until no photo can be added.

The problem

Input. An intrinsic matrix KK shared by all images (the method extends to one KiK_i per image), and the feature tracks of NN images: track jj lists the pixel uiju_{ij} of one scene point in each image ii that sees it. A threshold τ\tau on the reprojection error in pixels, 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 that could be registered, a point XjX_j for each track that could be triangulated, and the set of kept observations. After each run of line L9, every kept observation has a reprojection error of at most τ\tau, and every kept point has at least two kept observations. The first image aa has Ra=IR_a = I and ta=0t_a = 0, and the second image bb starts with ∥tb∥=1\|t_b\| = 1, so the result is fixed up to this similarity.

Coordinates. The code works in normalized image coordinates xij=K−1uijx_{ij} = K^{-1} u_{ij}, so a reprojection error ee in these coordinates is about fef e pixels for the focal length ff.

The algorithm

  1. INCREMENTAL-SFM(K, tracks, τ)
  2. 1(a, b) <- the image pair with the most common tracks
  3. 2(R_b, t_b), inliers <- RANSAC on the eight-point essential matrix with the Sampson error, then the decomposition with the most points in front; R_a <- I, t_a <- 0
  4. 3triangulate each inlier track from a and b, keep it if both errors are below τ
  5. 4bundle adjust all cameras and points with camera a fixed
  6. 5while some unregistered image sees at least 6 triangulated points
  7. 6c <- the unregistered image that sees the most triangulated points
  8. 7(R_c, t_c), inliers <- RANSAC on the six-point DLT pose, each fit refined by Gauss-Newton; add the inlier observations
  9. 8triangulate each new track seen by c and at least one other registered image; keep the views with error below τ, refit once, keep it if 2 views remain
  10. 9bundle adjust with camera a fixed; drop observations with error above τ and points with fewer than 2 observations
  11. 10return the cameras, the points and the kept observations

Line L1 uses the number of common tracks. Real systems also ask for a wide baseline, for example many inliers to the essential matrix but few to a homography, because a pair with a short baseline gives poorly conditioned depths. Line L2 uses the eight-point algorithm on normalized points, with Hartley normalization; the five-point algorithm is the usual choice in practice. The decomposition picks, among the four candidates of the essential matrix decomposition, the one that puts the most points in front of both cameras, the cheirality test. Line L7 is a DLT resection on 6 points, with its 3×33 \times 3 block projected to the nearest rotation. Calibrated minimal solvers such as P3P need fewer samples. Line L8 is linear triangulation. Lines L4 and L9 run Levenberg-Marquardt on the reprojection error and eliminate the points with the Schur complement, so the solve is on the reduced camera system.

Example

The reference test uses 5 cameras with f=800f = 800 px that look at a cube of 40 points from a distance of 5 units, each turned by up to 0.5 rad. 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:

  • There are 160 observations. Line L1 picks the pair (0,3)(0, 3) with 29 common tracks, and line L2 keeps 25 of them as inliers.
  • The loop registers the images in the order 2, 1, 4. Image 2 sees 20 triangulated points, and PnP keeps 16. Image 1 sees 25 and keeps 25. Image 4 sees 25 and keeps 24.
  • The result has 5 cameras, 36 points and 138 kept observations. The largest reprojection error is 1.30 px and the root mean square error is 0.52 px. After the best similarity to the truth, the largest point error is 0.033 units, in a scene of size 2.

On the same scene without noise or outliers, all 40 points are recovered to 10−610^{-6} after the similarity, as the correctness section predicts. These are benchmark results of the reference test.

Correctness

On exact data in general position, the method recovers every registered camera and every triangulated point exactly, up to the similarity fixed by the first pair (theorem). The reasons are: the eight-point method gives the exact essential matrix from 8 or more generic points, exactly one of its four decompositions puts the points in front of both cameras, linear triangulation from exact poses is exact, the DLT gives the exact pose from 6 or more points in general position, and bundle adjustment cannot move a solution with zero cost. The proof below gives the induction over the registration order. Each bundle adjustment never raises its cost, because Levenberg-Marquardt accepts only steps that lower it (theorem). With noise and outliers there is no guarantee: RANSAC finds an all-inlier sample only with high probability, bundle adjustment finds only a local minimum, and the order of the images matters (heuristic). The filter after each bundle adjustment makes sure that every kept point has at least two observations, each with an error of at most τ\tau (theorem).

Proof: Incremental SfM terminates, keeps its filter invariant and recovers exact generic data up to a similarityfull

We use the notation of the page and exact arithmetic, as in the real RAM model. The true cameras are (Ri∗,ti∗)(R_i^*, t_i^*) with Xc=Ri∗X+ti∗X_c = R_i^* X + t_i^*, the true points are Xj∗X_j^*, and the observations are xij=π(Ri∗Xj∗+ti∗)x_{ij} = \pi(R_i^* X_j^* + t_i^*) in normalized coordinates, with π(y)=(y1/y3,y2/y3)\pi(y) = (y_1 / y_3, y_2 / y_3) and y3>0y_3 > 0. The data are in general position in the following sense.

  • (G1) The first pair (a,b)(a, b) of line L1 has at least 8 common tracks, the two centers differ, and for every 8 of these tracks the conditioned eight-point system has a null space of dimension 1. No point lies on the line through the two centers.
  • (G2) For every image cc and every 6 points that cc sees, the DLT resection system has a null space of dimension 1. This excludes, for example, 6 points on one plane (Hartley and Zisserman, Chapter 7).
  • (G3) Each point is seen from at least two distinct centers that do not lie on one line with it, so its linear triangulation system has a null space of dimension 1.

Claim. (a) The loop of lines L5 to L9 runs at most N−2N - 2 times. (b) After each run of line L9, every kept observation has a reprojection error of at most τ\tau, and every kept point has at least two kept observations. (c) Each bundle adjustment returns a cost no larger than its start cost. (d) On exact data that satisfy (G1) to (G3), every camera and every point in the output equals the truth after one fixed similarity: with s=1/∥tb∗−Rb∗(Ra∗)Tta∗∥s = 1 / \|t_b^* - R_b^* (R_a^*)^{\mathsf T} t_a^*\|, the output is Ri=Ri∗(Ra∗)TR_i = R_i^* (R_a^*)^{\mathsf T}, ti=s(ti∗−Ri∗(Ra∗)Tta∗)t_i = s (t_i^* - R_i^* (R_a^*)^{\mathsf T} t_a^*) and Xj=s(Ra∗Xj∗+ta∗)X_j = s (R_a^* X_j^* + t_a^*).

Proof of (a). Each run of the loop either stops at line L5 or line L7, or adds a new image cc to the set of registered images. There are NN images and two are registered before the loop. □\square

Proof of (b). The filter of line L9 first deletes every observation with an error above τ\tau. It then deletes every point with fewer than two observations, together with its observations. The second deletion changes no error, so every observation left has an error of at most τ\tau, and every point left has at least two observations. □\square

Proof of (c). Levenberg-Marquardt in lines L4 and L9 computes a trial step and accepts it only if the new cost is strictly smaller than the current one. Otherwise it raises the damping and tries again, and it returns the current state when the damping passes its limit. So the cost never rises. □\square

Proof of (d). First we check the similarity. Put X′=s(Ra∗X+ta∗)X' = s (R_a^* X + t_a^*). Then X=(Ra∗)T(X′/s−ta∗)X = (R_a^*)^{\mathsf T} (X' / s - t_a^*) and

s(Ri∗X+ti∗)=Ri∗(Ra∗)TX′+s(ti∗−Ri∗(Ra∗)Tta∗)=RiX′+ti.s (R_i^* X + t_i^*) = R_i^* (R_a^*)^{\mathsf T} X' + s (t_i^* - R_i^* (R_a^*)^{\mathsf T} t_a^*) = R_i X' + t_i.

The camera coordinates are multiplied by s>0s > 0, so the projections and the signs of the depths do not change. So the transformed scene explains the same data, camera aa has (I,0)(I, 0), and camera bb has ∥tb∥=1\|t_b\| = 1. We call it the target, and show that the algorithm returns the target, by induction over the steps.

Line L2. In the target, the essential matrix E=[tb]×RbE = [t_b]_\times R_b satisfies xbjTExaj=0x_{bj}^{\mathsf T} E x_{aj} = 0 for every common track. By (G1), every sample of 8 tracks gives EE up to a nonzero scale, after the conditioning is undone. A true essential matrix has two equal nonzero singular values and one zero, so the projection to the singular values (1,1,0)(1, 1, 0) keeps it, up to scale. All Sampson errors are 0, so all common tracks are inliers, and the refit on them gives the same matrix. The four candidates of the decomposition are (UWVT,±u3)(U W V^{\mathsf T}, \pm u_3) and (UWTVT,±u3)(U W^{\mathsf T} V^{\mathsf T}, \pm u_3), and one of them is (Rb,tb)(R_b, t_b), since ∥tb∥=1\|t_b\| = 1. For a point that is not on the baseline, exactly one of the four candidates places it in front of both cameras. Both facts are in the section on the essential matrix of Hartley and Zisserman (Section 9.6). In the target, every point is in front of both cameras, so the true candidate counts every point, and each other candidate counts none. So line L2 returns (Rb,tb)(R_b, t_b).

Line L3. With exact poses, the true point is in the null space of the triangulation system of each track, and by (G3) that null space has dimension 1, so the triangulated point is the target point. Its errors are 0, so it is kept.

Line L4 and line L9. The cost of the target is 0. A step is accepted only if the cost becomes strictly smaller than 0, which is impossible, so bundle adjustment returns its start unchanged. Then no error exceeds τ\tau, and the filter deletes nothing, because every kept point has at least two observations.

Lines L6 and L7. By the induction hypothesis, all registered cameras and all triangulated points equal the target. Let cc be the chosen image. It sees at least 6 triangulated points. By (G2), any 6 of them give the DLT matrix λ[Rc∣tc]\lambda [R_c \mid t_c] for some λ≠0\lambda \ne 0, after the conditioning is undone. The sign fix makes det⁡(λRc)>0\det(\lambda R_c) > 0, so λ>0\lambda > 0. The singular values of λRc\lambda R_c are all λ\lambda, so the nearest rotation is RcR_c, and division by the mean singular value gives tct_c. The pose has zero residuals on the sample, so the Gauss-Newton refinement takes a zero step. All seen points then have error 0, so they are all inliers, the first sample already reaches the full count, and the final refit returns the same pose. So line L7 returns (Rc,tc)(R_c, t_c) and keeps every observation of cc of a triangulated point.

Line L8. Each new track is now seen by at least two registered cameras with target poses, and the triangulation is exact as for line L3. All errors are 0, so every view is kept.

So each step keeps the induction hypothesis, and at line L10 the output equals the target. ■\blacksquare

Complexity

In the real RAM model, the RANSAC loops have a fixed cap on the number of samples, and each sample costs O(n)O(n), so lines L2 and L7 cost O(n)O(n) per image. Line L8 scans the tracks, O(m)O(m) per image. Line L6 counts the seen points, O(m)O(m) per image. The bundle adjustment dominates. With N′N' registered cameras, one Levenberg-Marquardt iteration builds the reduced camera system in O(mN′)O(m N') time, because a point seen by dd cameras adds d2d^2 blocks and ∑d2≤N′m\sum d^2 \le N' m, and solves it densely in O(N′3)O(N'^3). With a fixed cap on the iterations, the bundle adjustments over all NN additions cost O(∑N′(mN′+N′3))=O(N2m+N4)O(\sum_{N'} (m N' + N'^3)) = O(N^2 m + N^4). The space is O(N2)O(N^2) for the reduced system plus O(m)O(m) for the data. This quadratic and quartic growth is why large systems run the full bundle adjustment only after the model has grown by some fraction, and use local bundle adjustment in between.

Properties

  • Randomized. RANSAC samples at random, so the result depends on the seed; the reference code fixes it.
  • Local. Bundle adjustment finds a local minimum near the start that the earlier steps give.
  • Order dependent. Different first pairs or image orders can give different results, and an early wrong registration can spoil the rest.
  • Drift. In long sequences without loops, small errors in the poses add up, as in scale drift of visual odometry.
  • Accurate. With repeated bundle adjustment and outlier filtering, it is among the most accurate SfM methods on benchmarks (benchmark result).

Variants and improvements

  • Next best view. COLMAP scores the candidate images by the number and the spread of their visible points over the image, not only by the count, to register well conditioned images first.
  • Local bundle adjustment. After each addition, adjust only the new camera and its neighbors; run the global adjustment after the model grows by a fixed fraction.
  • Robust triangulation. COLMAP triangulates with RANSAC over the pairs of views of a track and merges and completes tracks after each step.
  • Minimal solvers. Use the five-point method for the first pair and P3P for registration, both with a local optimization in RANSAC.
  • Hierarchical SfM. Split the images into clusters, reconstruct each one incrementally and merge the partial models.
  • Uncalibrated images. Add focal lengths and distortion to the bundle adjustment, with an initial focal length from the image metadata.

When to use it

Use it for unordered photo collections when accuracy matters more than speed, up to tens of thousands of images. It handles outliers well because each step is robust and each new image is checked against a model that is already reliable. For very large collections, or when a fast first result is needed, use global structure from motion, which solves for all cameras at once. For video in real time, use visual odometry or SLAM with keyframe selection.

Pitfalls

  • A short baseline in the first pair. The depths of the first points are then very uncertain, and the whole reconstruction can fail. Ask for a minimum triangulation angle.
  • Planar scenes. The eight-point method fails when all points lie on one plane, and so does the six-point DLT for PnP. The five-point method and P3P still work for planar points, and a homography can start the reconstruction.
  • Repetitive structures. Symmetric buildings give wrong matches that agree with each other, which RANSAC cannot reject, and the result can fold onto itself.
  • The gauge. Fixing one camera leaves the global scale free. Levenberg-Marquardt copes because of its damping, but a solver without damping needs a scale constraint as well.
  • Points behind the camera. Check the depth sign in every reprojection error, or the bundle adjustment can move points through the camera.

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()
incremental_structure_from_motion.py 398 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incremental-structure-from-motion/. The authors are listed in prov/K15KYC.jsonl.

"""Incremental 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 that could be registered, with X_c = R X + t, and a 3D point for
every track that could be triangulated. Image a of the first pair has
R = I and t = 0, and image b has ||t|| = 1; the reconstruction is fixed
only up to this similarity.

The pipeline: pick the image pair with the most common tracks, find its
relative pose from the essential matrix (RANSAC on the 8-point method),
triangulate, run bundle adjustment. Then repeat: register the image that
sees the most triangulated points by a RANSAC on the 6-point DLT,
triangulate the tracks that it makes visible in two images, run bundle
adjustment, and drop observations with a reprojection error above tau.
"""

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

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

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


# ------------------------------------------------------------ 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). The
    points are conditioned first (Hartley normalization)."""
    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; 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):
            best, best_e = inl, e
            need = ransac_count(len(best) / n, 8, cap)
    e = eight_point_essential([x1[k] for k in best], [x2[k] for k in best])
    refit = [k for k in range(n) if sampson(e, x1[k], x2[k]) < tau]
    if len(refit) >= len(best):
        best = refit
    else:
        e = best_e
    pose = decompose_essential(e, [x1[k] for k in best], [x2[k] for k in best])
    return pose, best


def dlt_pnp(xs: Sequence[Vector], ps: Sequence[Sequence[float]]) -> Optional[Pose]:
    """Pose from six or more 3D points and normalized image points, by the
    DLT on a conditioned copy of the points, then the nearest rotation."""
    n = len(xs)
    c = [sum(x[a] for x in xs) / n for a in range(3)]
    s = sum(math.dist(x, c) for x in xs) / n or 1.0
    rows = []
    for x, p in zip(xs, ps):
        y = [(x[a] - c[a]) / s for a in range(3)] + [1.0]
        rows.append(y + [0.0] * 4 + [-p[0] * v for v in y])
        rows.append([0.0] * 4 + y + [-p[1] * v for v in y])
    h = nullvec(rows)
    pc = [h[0:4], h[4:8], h[8:12]]
    # undo the conditioning: P = P' [[I / s, -c / s], [0, 1]]
    m = [[pc[a][b] / s for b in range(3)] for a in range(3)]
    p4 = [pc[a][3] - sum(m[a][b] * c[b] for b in range(3)) for a in range(3)]
    if det(m) < 0:
        m = [[-v for v in row] for row in m]
        p4 = [-v for v in p4]
    u, sv, v = svd(m)
    r = mul(u, transpose(v))
    k = sum(sv) / 3.0
    if k <= 0:
        return None
    return r, [v_ / k for v_ in p4]


def pnp_ransac(xs: Sequence[Vector], ps: Sequence[Vector], tau: float,
               rng: random.Random, cap: int = 200) -> Tuple[Optional[Pose], List[int]]:
    """RANSAC on the 6-point DLT, each fit polished by Gauss-Newton on the
    pose. Returns the pose and the inlier indices, or (None, [])."""
    n = len(xs)
    best: List[int] = []
    best_pose = None
    it, need = 0, cap
    while it < need:
        it += 1
        s = rng.sample(range(n), 6)
        pose = dlt_pnp([xs[k] for k in s], [ps[k] for k in s])
        if pose is None:
            continue
        pose = refine_pose(pose, [xs[k] for k in s], [ps[k] for k in s])
        inl = [k for k in range(n) if reproj_error(pose, xs[k], ps[k]) < tau]
        if len(inl) > len(best):
            best, best_pose = inl, pose
            need = ransac_count(len(best) / n, 6, cap)
    if len(best) < 6:
        return None, []
    pose = refine_pose(best_pose, [xs[k] for k in best], [ps[k] for k in best])
    best = [k for k in range(n) if reproj_error(pose, xs[k], ps[k]) < tau]
    return pose, best


def refine_pose(pose: Pose, xs: Sequence[Vector], ps: Sequence[Vector], iters: int = 5) -> Pose:
    """A few Gauss-Newton steps on the reprojection error of one camera."""
    for _ in range(iters):
        h = [[0.0] * 6 for _ in range(6)]
        g = [0.0] * 6
        for x, p in zip(xs, ps):
            if to_cam(pose, x)[2] <= 0:
                return pose
            res, a, _ = _blocks(pose, x, p)
            for r in range(6):
                g[r] -= a[0][r] * res[0] + a[1][r] * res[1]
                for s in range(6):
                    h[r][s] += a[0][r] * a[0][s] + a[1][r] * a[1][s]
        try:
            d = solve(h, g)
        except ValueError:
            return pose
        r, t = pose
        pose = (mul(axis_angle_to_R(d[0:3]), r), [t[k] + d[3 + k] for k in range(3)])
        if max(abs(v) for v in d) < 1e-12:
            break
    return pose


# ---------------------------------------------------- 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]]
    # dX_c/dw = -[R X]_x, dX_c/dt = I, dX_c/dX = R
    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 incremental_structure_from_motion(K: Matrix, tracks: Sequence[Dict[int, Sequence[float]]],
                                      tau_px: float = 3.0, 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]
    images = sorted({i for tr in tracks for i in tr})
    pair_count: Dict[Tuple[int, int], int] = {}
    for tr in tracks:
        ims = sorted(tr)
        for x in range(len(ims)):
            for y in range(x + 1, len(ims)):
                pair_count[(ims[x], ims[y])] = pair_count.get((ims[x], ims[y]), 0) + 1
    a, b = max(sorted(pair_count), key=lambda k: pair_count[k])  # @line L1
    common = [j for j, tr in enumerate(tracks) if a in tr and b in tr]
    pose_b, inl = relative_pose_ransac([xn[j][a] for j in common], [xn[j][b] for j in common],
                                       tau, rng)  # @line L2
    cams: Dict[int, Pose] = {a: (EYE3, [0.0, 0.0, 0.0]), b: pose_b}
    pts: Dict[int, Vector] = {}
    obs: Dict[Tuple[int, int], Vector] = {}
    for k in inl:  # @line L3
        j = common[k]
        x = triangulate([cams[a], cams[b]], [xn[j][a], xn[j][b]])
        if all(reproj_error(cams[i], x, xn[j][i]) < tau for i in (a, b)):
            pts[j] = x
            obs[(a, j)], obs[(b, j)] = xn[j][a], xn[j][b]
    cams, pts = bundle_adjust(cams, pts, obs, a)  # @line L4
    while True:  # @line L5
        left = [i for i in images if i not in cams]
        seen = {i: [j for j in pts if i in tracks[j]] for i in left}
        if not left or max(len(s) for s in seen.values()) < 6:
            break
        c = max(left, key=lambda i: (len(seen[i]), -i))  # @line L6
        js = seen[c]
        pose, inl = pnp_ransac([pts[j] for j in js], [xn[j][c] for j in js], tau, rng)  # @line L7
        if pose is None:
            break
        cams[c] = pose
        for k in inl:
            obs[(c, js[k])] = xn[js[k]][c]
        for j, tr in enumerate(tracks):  # @line L8
            views = [i for i in tr if i in cams]
            if j in pts or c not in tr or len(views) < 2:
                continue
            x = triangulate([cams[i] for i in views], [xn[j][i] for i in views])
            good = [i for i in views if reproj_error(cams[i], x, xn[j][i]) < tau]
            if 2 <= len(good) < len(views):
                x = triangulate([cams[i] for i in good], [xn[j][i] for i in good])
                good = [i for i in good if reproj_error(cams[i], x, xn[j][i]) < tau]
            if len(good) >= 2:
                pts[j] = x
                for i in good:
                    obs[(i, j)] = xn[j][i]
        cams, pts = bundle_adjust(cams, pts, obs, a)  # @line L9
        for key in [k for k in obs if reproj_error(cams[k[0]], pts[k[1]], obs[k]) > tau]:
            del obs[key]
        for j in list(pts):
            if sum(1 for (i, 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]
    return cams, pts, set(obs)  # @line L10
test_incremental_structure_from_motion.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incremental-structure-from-motion/. The authors are listed in prov/K15KYC.jsonl.

import math
import random

from cvgeom import random_scene
from cvla import det, inv, matvec, mul, svd, transpose
from incremental_structure_from_motion import (EYE3, ba_cost, bundle_adjust, dlt_pnp,
                                               incremental_structure_from_motion, normalize,
                                               relative_pose_ransac, reproj_error)


def make_tracks(seed, n_cams=5, n_pts=40, visible=0.8, noise=0.0, outliers=0.0):
    rng = random.Random(seed)
    sc = random_scene(rng, n=n_pts, n_cams=n_cams, max_angle=0.5, distance=5.0)
    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 point_error(sc, pts):
    js = sorted(pts)
    s, r, t = umeyama([pts[j] for j in js], [sc["X"][j] for j in js])
    errs = [math.dist([s * x + t[a] for a, x in enumerate(matvec(r, pts[j]))], sc["X"][j]) for j in js]
    return max(errs)


def test_exact_tracks_give_the_true_scene_up_to_similarity():
    sc, tracks = make_tracks(1)
    cams, pts, obs = incremental_structure_from_motion(sc["K"][0], tracks)
    assert sorted(cams) == list(range(5))
    assert len(pts) == 40
    assert point_error(sc, pts) < 1e-6
    a = [i for i in cams if cams[i][0] == EYE3 and cams[i][1] == [0.0, 0.0, 0.0]]
    assert len(a) == 1


def test_noise_and_outliers():
    sc, tracks = make_tracks(2, n_cams=5, n_pts=40, noise=0.5, outliers=0.05)
    cams, pts, obs = incremental_structure_from_motion(sc["K"][0], tracks, tau_px=3.0)
    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
    # the shape error is small compared with the scene size of 2 units
    assert point_error(sc, pts) < 0.05


def test_relative_pose_matches_the_truth():
    rng = random.Random(3)
    sc = random_scene(rng, n=30, n_cams=2, first_identity=True, max_angle=0.5)
    kinv = inv(sc["K"][0])
    x1 = [normalize(kinv, p) for p in sc["x"][0]]
    x2 = [normalize(kinv, p) for p in sc["x"][1]]
    (r, t), inl = relative_pose_ransac(x1, x2, 1e-3, rng)
    assert len(inl) == 30
    tt = sc["t"][1]
    n = math.sqrt(sum(v * v for v in tt))
    assert max(abs(a - b) for ra, rb in zip(r, sc["R"][1]) for a, b in zip(ra, rb)) < 1e-8
    assert max(abs(a - b / n) for a, b in zip(t, tt)) < 1e-8


def test_dlt_pnp_is_exact_on_exact_data():
    rng = random.Random(4)
    sc = random_scene(rng, n=10, n_cams=1, max_angle=1.0)
    kinv = inv(sc["K"][0])
    r, t = dlt_pnp(sc["X"], [normalize(kinv, p) for p in sc["x"][0]])
    assert max(abs(a - b) for ra, rb in zip(r, sc["R"][0]) for a, b in zip(ra, rb)) < 1e-8
    assert max(abs(a - b) for a, b in zip(t, sc["t"][0])) < 1e-8


def test_bundle_adjustment_lowers_the_cost():
    sc, tracks = make_tracks(5, n_cams=3, n_pts=15, visible=1.0, noise=1.0)
    kinv = inv(sc["K"][0])
    rng = random.Random(5)
    cams = {i: (sc["R"][i], sc["t"][i]) for i in range(3)}
    pts = {j: [x + rng.gauss(0, 0.05) for x in sc["X"][j]] for j in range(15)}
    obs = {(i, j): normalize(kinv, tracks[j][i]) for j in range(15) for i in tracks[j]}
    f0 = ba_cost(cams, pts, obs)
    cams2, pts2 = bundle_adjust(cams, pts, obs, 0)
    assert ba_cost(cams2, pts2, obs) < 0.01 * f0

History

Sequential reconstruction from image sequences, which adds one view at a time to a projective or metric model, was developed in the 1990s, for example by Beardsley, Zisserman and Murray and by Pollefeys and colleagues. Snavely, Seitz and Szeliski (2006) applied the incremental scheme to unordered photo collections from the Internet in Photo Tourism and its software Bundler, with a bundle adjustment after each new camera. Schönberger and Frahm (2016) revisited each step, with a new next best view score, robust triangulation and iterative filtering, in COLMAP, which became the standard open tool.

References

  1. Noah Snavely, Steven M. Seitz and Richard Szeliski, Photo tourism: exploring photo collections in 3D, ACM Transactions on Graphics 25(3), 2006, 835-846, the structure from motion section (the initial pair, the addition of one camera at a time, the bundle adjustment after each addition)
  2. Johannes L. Schönberger and Jan-Michael Frahm, Structure-from-motion revisited, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2016), 4104-4113, the whole paper (the initialization, the next best view selection, robust triangulation, bundle adjustment and filtering)
  3. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Chapter 7 (camera resectioning by the DLT), Chapter 9 (the essential matrix and its four decompositions), Chapter 12 (triangulation) and Chapter 18 (N-view methods)
  4. Bill Triggs, Philip F. McLauchlan, Richard I. Hartley and Andrew W. Fitzgibbon, Bundle adjustment, a modern synthesis, Vision Algorithms: Theory and Practice, Lecture Notes in Computer Science 1883, Springer, 2000, 298-372, the sections on the sparse normal equations and the Schur complement
  5. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 11, Structure from motion and SLAM (the section on multi-frame structure from motion)

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