> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Poses and Points from Many Views

> Camera poses and 3D points recovered from a set of photos.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/3d-reconstruction/structure-from-motion/index.ipynb)

*This section follows Chapter 44 of [*Foundations of Computer Vision*](https://visionbook.mit.edu/multiview.html) by Antonio Torralba, Phillip Isola, and William T. Freeman. The book's own figures are not reproduced here.*

[Depth from Two Views](https://aegean.ai/aiml-common/lectures/3d-reconstruction/stereo-vision/index.md) recovers depth when you already know where the two cameras are. Structure from motion drops that assumption. You start from a set of photos of a scene, taken from unknown positions, and you recover two things at once: the pose of every camera and the 3D position of the points the photos share. The poses are the *motion*, the points are the *structure*.

In this section you build the method yourself on real photos. You match features between two views, estimate the essential matrix, recover the relative pose, triangulate points, and then add views one at a time while bundle adjustment refines everything. At the end you compare your cameras with a reconstruction of all the photos made with COLMAP, a widely used structure-from-motion system that [Structure from Motion at Scale](https://aegean.ai/aiml-common/lectures/3d-reconstruction/colmap/index.md) covers in its own section.

## Unknowns and measurements

Suppose $M$ cameras observe $N$ points, and every point is visible in every image. Each observation is a pixel, so it gives two numbers, and there are $2NM$ of them. The unknowns are three coordinates per point and six pose parameters per camera (three for rotation, three for translation), so $3N + 6M$ in total.

Not all of these unknowns can be determined. If you rotate, translate and scale the whole scene together with the cameras, every image stays exactly the same. That freedom has seven degrees: three for rotation, three for translation and one for scale. It is called the *gauge freedom*. The images can only fix the reconstruction up to such a similarity transform, so the problem has a chance of being determined when

$$
2NM \;\ge\; 3N + 6M - 7 .
$$

Two cameras and five points give $20 \ge 20$, which is why five correspondences are the minimum for the relative pose of two calibrated cameras. In practice you have thousands of points and many cameras, so the system is heavily overdetermined, and the work goes into finding correct correspondences and solving a large nonlinear least-squares problem.

You will fix the gauge yourself: the first camera sits at the origin with the identity rotation, and the scale is whatever the first two views give. At the end, a similarity transform maps your reconstruction onto COLMAP's.

> [accordion] Code
>
> ```python theme={null}
> import struct
> from pathlib import Path
>
> import cv2
> import matplotlib.pyplot as plt
> import numpy as np
> import torch
> from huggingface_hub import snapshot_download
>
> from cycler import cycler
> from matplotlib_inline.backend_inline import set_matplotlib_formats
> set_matplotlib_formats("svg")
> FIG_GRAY = "#808080"
> FIG_COLORS = ["#0072B2", "#D55E00", "#009E73", "#cb77a6", "#c28600", "#1d99e0", "#7f7f7f"]
> plt.rcParams.update({
>     "figure.facecolor": "none", "axes.facecolor": "none",
>     "savefig.facecolor": "none", "savefig.transparent": True,
>     "text.color": FIG_GRAY, "axes.labelcolor": FIG_GRAY, "axes.edgecolor": FIG_GRAY,
>     "xtick.color": FIG_GRAY, "ytick.color": FIG_GRAY,
>     "grid.color": FIG_GRAY, "grid.alpha": 0.25,
>     "legend.facecolor": "none", "legend.edgecolor": FIG_GRAY, "legend.framealpha": 0,
>     "axes.prop_cycle": cycler(color=FIG_COLORS),
>     "svg.hashsalt": "aiml", "svg.fonttype": "path",
> })
>
> torch.set_default_dtype(torch.float64)
> rng = np.random.default_rng(0)
> cv2.setRNGSeed(0)
> ```

## The scene

The photos are the *garden* scene of the Mip-NeRF 360 dataset: 185 photos taken while walking around a table in a garden. You use the copies downsampled by a factor of eight, about $650 \times 420$ pixels. The dataset also ships a COLMAP reconstruction of the full set, made by the dataset's authors and not rerun here, as three binary files: `cameras.bin` holds the intrinsics, `images.bin` the pose of each photo and the pixels it observed, and `points3D.bin` the sparse points with their colors. The reader below parses them, so you can compare against them later.

> [accordion] Code
>
> ```python theme={null}
> DATA = Path(snapshot_download(
>     "mileleap/mipnerf360", repo_type="dataset",
>     allow_patterns=["garden/images_8/*", "garden/sparse/*"],
> )) / "garden"
>
> CAMERA_MODEL_PARAMS = {0: 3, 1: 4, 2: 4, 3: 5, 4: 8, 5: 8, 6: 12, 7: 5, 8: 4, 9: 5, 10: 12}
>
>
> def read_cameras(path):
>     cams = {}
>     with open(path, "rb") as f:
>         (n,) = struct.unpack("<Q", f.read(8))
>         for _ in range(n):
>             cam_id, model, w, h = struct.unpack("<iiQQ", f.read(24))
>             k = CAMERA_MODEL_PARAMS[model]
>             params = np.array(struct.unpack(f"<{k}d", f.read(8 * k)))
>             cams[cam_id] = dict(model=model, width=w, height=h, params=params)
>     return cams
>
>
> def qvec_to_rotmat(q):
>     w, x, y, z = q
>     return np.array([
>         [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 read_images(path):
>     imgs = {}
>     with open(path, "rb") as f:
>         (n,) = struct.unpack("<Q", f.read(8))
>         for _ in range(n):
>             img_id = struct.unpack("<i", f.read(4))[0]
>             q = np.array(struct.unpack("<4d", f.read(32)))
>             t = np.array(struct.unpack("<3d", f.read(24)))
>             cam_id = struct.unpack("<i", f.read(4))[0]
>             name = b""
>             while (c := f.read(1)) != b"\x00":
>                 name += c
>             (n2d,) = struct.unpack("<Q", f.read(8))
>             data = np.frombuffer(f.read(24 * n2d), dtype=[("xy", "<f8", 2), ("pid", "<i8")])
>             imgs[name.decode()] = dict(id=img_id, R=qvec_to_rotmat(q), t=t, cam_id=cam_id,
>                                        xy=data["xy"].copy(), pid=data["pid"].copy())
>     return imgs
>
>
> def read_points3d(path):
>     with open(path, "rb") as f:
>         (n,) = struct.unpack("<Q", f.read(8))
>         xyz, rgb, err = np.empty((n, 3)), np.empty((n, 3), np.uint8), np.empty(n)
>         for i in range(n):
>             _, x, y, z = struct.unpack("<Q3d", f.read(32))
>             xyz[i] = (x, y, z)
>             rgb[i] = np.frombuffer(f.read(3), np.uint8)
>             err[i], track_len = struct.unpack("<dQ", f.read(16))
>             f.read(8 * track_len)
>     return xyz, rgb, err
>
>
> cameras = read_cameras(DATA / "sparse/0/cameras.bin")
> colmap_images = read_images(DATA / "sparse/0/images.bin")
> colmap_xyz, colmap_rgb, colmap_err = read_points3d(DATA / "sparse/0/points3D.bin")
>
> names = sorted(colmap_images)
> img0 = cv2.imread(str(DATA / "images_8" / names[0]))
> H, W = img0.shape[:2]
> cam = cameras[colmap_images[names[0]]["cam_id"]]
> fx, fy, cx, cy = cam["params"][:4]
> sx, sy = W / cam["width"], H / cam["height"]
> K = np.array([[fx * sx, 0, cx * sx], [0, fy * sy, cy * sy], [0, 0, 1.0]])
> print(f"{len(names)} photos, camera model {cam['model']} (1 = pinhole), "
>       f"full size {cam['width']} x {cam['height']}, downsampled to {W} x {H}")
> print("K for the downsampled photos:\n", K.round(1))
> print(f"COLMAP model: {len(colmap_images)} registered photos, {len(colmap_xyz)} sparse points")
> ```

```output theme={null}
185 photos, camera model 1 (1 = pinhole), full size 5187 x 3361, downsampled to 648 x 420
K for the downsampled photos:
 [[480.3   0.  324. ]
 [  0.  481.4 210. ]
 [  0.    0.    1. ]]
COLMAP model: 185 registered photos, 138766 sparse points
```

You treat the intrinsic matrix $K$ as known. That is the *calibrated* case: [camera calibration](https://aegean.ai/aiml-common/lectures/sensor-models/cameras/camera-modeling/index.md) measures $K$ once, and structure from motion then only has to find the poses and the points. With $K$ known, a pixel $\mathbf{u}$ in homogeneous coordinates becomes a viewing direction $\mathbf{x} = K^{-1}\mathbf{u}$, and the geometry below works with those normalized coordinates.

You use a run of twelve consecutive photos, which covers a short arc of the walk around the table.

> [accordion] Code
>
> ```python theme={null}
> VIEW_NAMES = names[20:32]
> images = [cv2.imread(str(DATA / "images_8" / n))[..., ::-1].copy() for n in VIEW_NAMES]
> gray = [cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) for im in images]
> print(VIEW_NAMES)
> ```

```output theme={null}
['DSC07976.JPG', 'DSC07977.JPG', 'DSC07978.JPG', 'DSC07979.JPG', 'DSC07980.JPG', 'DSC07981.JPG', 'DSC07982.JPG', 'DSC07983.JPG', 'DSC07984.JPG', 'DSC07985.JPG', 'DSC07986.JPG', 'DSC07987.JPG']
```

![Twelve photos of the garden scene in a grid, all showing a round wooden table with a vase on it, a lawn and bushes behind. The viewpoint moves a little to the side from one photo to the next.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/structure-from-motion/images/cell_4_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=2dcf76ac2c41c78d159b1ca9e33324b5)

## Features and matches

Structure from motion needs pixels in different photos that show the same 3D point. You find them in two steps, as Chapter 44 of the book describes. An interest point detector picks distinctive locations, such as corners and blobs, at several scales. A descriptor then summarizes the patch around each location as a vector that changes little with viewpoint and lighting. Here the detector and descriptor are SIFT: each keypoint gets a 128-dimensional histogram of gradient orientations.

Two keypoints match when their descriptors are close. A nearest-neighbor match alone is unreliable on repeated texture such as grass and leaves, where many patches look alike. The *ratio test* keeps a match only when the nearest descriptor is clearly closer than the second nearest, here by a factor of $0.8$. Matches that pass can still be wrong, and the geometry below removes most of the rest.

> [accordion] Code
>
> ```python theme={null}
> sift = cv2.SIFT_create(nfeatures=8000, contrastThreshold=0.02)
> feats = [sift.detectAndCompute(g, None) for g in gray]
> kps = [np.array([k.pt for k in kp]) for kp, _ in feats]
> descs = [d for _, d in feats]
> matcher = cv2.BFMatcher(cv2.NORM_L2)
>
>
> def match(i, j, ratio=0.8):
>     # index pairs (keypoint in view i, keypoint in view j) that pass the ratio test
>     pairs = matcher.knnMatch(descs[i], descs[j], k=2)
>     good = [(m.queryIdx, m.trainIdx) for m, n in pairs if m.distance < ratio * n.distance]
>     return np.array(good, dtype=int)
>
>
> m01 = match(0, 2)
> print("keypoints per view:", [len(k) for k in kps])
> print(f"matches between views 0 and 2 after the ratio test: {len(m01)}")
> ```

```output theme={null}
keypoints per view: [3534, 3456, 3364, 3451, 3376, 3279, 3348, 3330, 3538, 3454, 3566, 3748]
matches between views 0 and 2 after the ratio test: 340
```

![Two garden photos side by side with green lines joining matched keypoints. Most lines are nearly horizontal and parallel, joining the same spot on the table or bushes; a few cross the others at steep angles.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/structure-from-motion/images/cell_6_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=2f20f2956f9324ba41447f417d33d56c)

## The essential matrix

Place the first camera at the origin, so a point $\mathbf{X}$ has coordinates $\mathbf{X}$ in its frame, and the second camera at rotation $R$ and translation $\mathbf{t}$, so the same point has coordinates $R\mathbf{X} + \mathbf{t}$ there. The normalized image points are $\mathbf{x} \propto \mathbf{X}$ and $\mathbf{x}' \propto R\mathbf{X} + \mathbf{t}$.

The three vectors $\mathbf{x}'$, $\mathbf{t}$ and $R\mathbf{x}$ all lie in one plane, the *epipolar plane* through the two camera centers and the point. Three coplanar vectors have a zero triple product:

$$
\mathbf{x}'^{\top} \big(\mathbf{t} \times R\mathbf{x}\big) = 0 .
$$

Write the cross product with $\mathbf{t}$ as multiplication by the skew-symmetric matrix $[\mathbf{t}]_\times$. The constraint becomes

$$
\mathbf{x}'^{\top} E\,\mathbf{x} = 0, \qquad E = [\mathbf{t}]_\times R .
$$

$E$ is the *essential matrix*. It is defined only up to scale, because $\mathbf{t}$ can be scaled without changing the constraint, so it has five degrees of freedom: three for $R$ and two for the direction of $\mathbf{t}$. A valid essential matrix has two equal singular values and a third that is zero. In pixel coordinates the same constraint reads $\mathbf{u}'^{\top} F \mathbf{u} = 0$ with the fundamental matrix $F = K^{-\top} E K^{-1}$.

For one point $\mathbf{x}$ in the first image, $E\mathbf{x}$ is a line in the second image, the *epipolar line*, and the match $\mathbf{x}'$ must lie on it.

### Estimating E with RANSAC

Each correspondence gives one equation that is linear in the nine entries of $E$. Stack eight of them into an $8 \times 9$ matrix $A$ and take the null vector of $A$ (the right singular vector with the smallest singular value). This is the *eight-point algorithm*. Afterwards you project the result onto the set of valid essential matrices by replacing its singular values with $(1, 1, 0)$. The *five-point algorithm* uses the minimum of five correspondences and is what production systems run, but it needs a polynomial solver; eight points keep everything linear (Hartley & Zisserman, 2004).

Some matches are wrong, and one wrong match ruins a least-squares fit. RANSAC handles this by repetition. Draw eight random matches, fit $E$, and count how many of all the matches agree with it within a threshold. Keep the $E$ with the most agreement, then refit it on all of its inliers. The agreement test below is the *Sampson distance*, a first-order approximation of the distance in pixels from a match to its epipolar lines.

> [accordion] Code
>
> ```python theme={null}
> def to_normalized(uv):
>     return (np.linalg.inv(K) @ np.column_stack([uv, np.ones(len(uv))]).T).T
>
>
> def skew(v):
>     return np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
>
>
> def eight_point(x1, x2):
>     A = np.column_stack([x2[:, [0]] * x1, x2[:, [1]] * x1, x2[:, [2]] * x1])
>     E = np.linalg.svd(A)[2][-1].reshape(3, 3)
>     U, _, Vt = np.linalg.svd(E)
>     return U @ np.diag([1.0, 1.0, 0.0]) @ Vt
>
>
> def sampson_px(E, x1, x2):
>     # Sampson distance, converted to pixels with the mean focal length
>     Ex1, Etx2 = x1 @ E.T, x2 @ E
>     num = np.sum(x2 * Ex1, axis=1) ** 2
>     den = Ex1[:, 0] ** 2 + Ex1[:, 1] ** 2 + Etx2[:, 0] ** 2 + Etx2[:, 1] ** 2
>     return np.sqrt(num / den) * K[0, 0]
>
>
> def ransac_essential(x1, x2, thresh_px=1.0, iters=2000):
>     best = np.zeros(len(x1), bool)
>     for _ in range(iters):
>         s = rng.choice(len(x1), 8, replace=False)
>         inl = sampson_px(eight_point(x1[s], x2[s]), x1, x2) < thresh_px
>         if inl.sum() > best.sum():
>             best = inl
>     E = eight_point(x1[best], x2[best])
>     return E, sampson_px(E, x1, x2) < thresh_px
>
>
> x1 = to_normalized(kps[0][m01[:, 0]])
> x2 = to_normalized(kps[2][m01[:, 1]])
> E01, inl01 = ransac_essential(x1, x2)
> print(f"RANSAC inliers: {inl01.sum()} of {len(inl01)} matches")
> print("singular values of E (scaled):", (np.linalg.svd(E01)[1] / np.linalg.svd(E01)[1][0]).round(4))
> ```

```output theme={null}
RANSAC inliers: 282 of 340 matches
singular values of E (scaled): [1. 1. 0.]
```

![Left, view 0 with twelve colored dots on the table and bushes. Right, view 2 with twelve lines of the same colors, each passing through a dot of its color, the matched point.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/structure-from-motion/images/cell_8_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=0d47e14c228ad06c5c365b813b6734d9)

Each match in view 2 sits on the epipolar line of its point in view 0. The lines are nearly parallel and nearly horizontal because the camera moved mostly sideways between the two photos.

## Relative pose and triangulation

Factor $E = U \operatorname{diag}(1, 1, 0) V^{\top}$ with $W = \begin{bmatrix} 0 & -1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix}$. The rotation is $R = U W V^{\top}$ or $R = U W^{\top} V^{\top}$, and the translation direction is $\mathbf{t} = \pm \mathbf{u}_3$, the last column of $U$ (Hartley & Zisserman, 2004). That gives four candidate poses. Only one of them puts the scene in front of both cameras; the other three place the points behind one camera or both. So you triangulate the inliers with each candidate and keep the pose with the most points at positive depth in both views. This is the *cheirality check*.

Triangulation intersects two viewing rays. With projection matrices $P = [I \mid \mathbf{0}]$ and $P' = [R \mid \mathbf{t}]$ and the homogeneous point $\tilde{\mathbf{X}}$, the constraint $\mathbf{x} \times P\tilde{\mathbf{X}} = \mathbf{0}$ gives two independent linear equations per view:

$$
\begin{aligned}
\big(x\,\mathbf{p}_3^{\top} - \mathbf{p}_1^{\top}\big)\tilde{\mathbf{X}} &= 0, \\
\big(y\,\mathbf{p}_3^{\top} - \mathbf{p}_2^{\top}\big)\tilde{\mathbf{X}} &= 0,
\end{aligned}
$$

where $\mathbf{p}_k^{\top}$ is the $k$-th row of $P$. Stack the four equations of the two views and take the null vector. This is the *direct linear transform* (DLT). Noise means the two rays do not quite meet, and the DLT returns a point close to both.

> [accordion] Code
>
> ```python theme={null}
> def triangulate(P1, P2, x1, x2):
>     A = np.stack([
>         x1[:, [0]] * P1[2] - P1[0], x1[:, [1]] * P1[2] - P1[1],
>         x2[:, [0]] * P2[2] - P2[0], x2[:, [1]] * P2[2] - P2[1],
>     ], axis=1)
>     X = np.linalg.svd(A)[2][:, -1]
>     return X[:, :3] / X[:, 3:]
>
>
> def pose_candidates(E):
>     U, _, Vt = np.linalg.svd(E)
>     if np.linalg.det(U) < 0: U = -U
>     if np.linalg.det(Vt) < 0: Vt = -Vt
>     Wm = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1.0]])
>     return [(R, s * U[:, 2]) for R in (U @ Wm @ Vt, U @ Wm.T @ Vt) for s in (1, -1)]
>
>
> P0 = np.hstack([np.eye(3), np.zeros((3, 1))])
> counts = []
> for R, t in pose_candidates(E01):
>     X = triangulate(P0, np.hstack([R, t[:, None]]), x1[inl01], x2[inl01])
>     counts.append(np.sum((X[:, 2] > 0) & ((X @ R.T + t)[:, 2] > 0)))
> print("points in front of both cameras, per candidate pose:", counts)
> R01, t01 = pose_candidates(E01)[int(np.argmax(counts))]
> print("rotation angle between the views: "
>       f"{np.degrees(np.arccos((np.trace(R01) - 1) / 2)):.1f} degrees")
> ```

```output theme={null}
points in front of both cameras, per candidate pose: [np.int64(282), np.int64(0), np.int64(0), np.int64(0)]
rotation angle between the views: 26.6 degrees
```

One candidate keeps essentially all points in front of both cameras, and the other three keep few or none. The translation has unit length because the essential matrix carries no scale. That unit is the scale of your whole reconstruction, the seventh gauge degree of freedom.

## Reprojection error and bundle adjustment

The linear steps above minimize algebraic quantities that have no direct meaning in the image. The quantity you care about is the *reprojection error*: project each 3D point into every camera that saw it and measure the distance in pixels to the observed keypoint. With the projection $\pi(\mathbf{X}) = \big(X/Z,\; Y/Z\big)$ followed by $K$, camera $j$ predicts point $i$ at

$$
\hat{\mathbf{u}}_{ij} = K\,\pi\big(R_j \mathbf{X}_i + \mathbf{t}_j\big).
$$

*Bundle adjustment* minimizes the total reprojection error over all poses and points together (Triggs et al., 2000):

$$
\min_{\{R_j, \mathbf{t}_j\},\, \{\mathbf{X}_i\}} \;\sum_{(i,j)\,\in\,\mathcal{O}} \rho\Big(\big\lVert \hat{\mathbf{u}}_{ij} - \mathbf{u}_{ij} \big\rVert\Big),
$$

where $\mathcal{O}$ is the set of observations. The name comes from the bundles of rays that leave each camera and are adjusted until they pass through the points. Three details make the problem solvable in practice:

* Each rotation is stored as an axis-angle vector $\boldsymbol{\omega}$, with $R = \exp([\boldsymbol{\omega}]_\times)$ given by the Rodrigues formula. Three unconstrained numbers keep $R$ a rotation during the optimization.
* $\rho$ is the Huber loss, quadratic for small residuals and linear for large ones, so a few remaining bad matches cannot dominate.
* The first camera stays fixed at the origin. That removes six of the seven gauge degrees of freedom; the scale stays at the one set by the first two views.

Production solvers use Levenberg-Marquardt with the sparse structure of the Jacobian. Here the problem is small enough for a quasi-Newton method with automatic differentiation.

> [accordion] Code
>
> ```python theme={null}
> def rodrigues(w):
>     theta = torch.sqrt((w * w).sum(-1, keepdim=True) + 1e-24)
>     k = w / theta
>     Kx = torch.zeros(w.shape[:-1] + (3, 3), dtype=w.dtype)
>     Kx[..., 0, 1], Kx[..., 0, 2] = -k[..., 2], k[..., 1]
>     Kx[..., 1, 0], Kx[..., 1, 2] = k[..., 2], -k[..., 0]
>     Kx[..., 2, 0], Kx[..., 2, 1] = -k[..., 1], k[..., 0]
>     th = theta[..., None]
>     return torch.eye(3) + torch.sin(th) * Kx + (1 - torch.cos(th)) * Kx @ Kx
>
>
> def rotmat_to_axis_angle(R):
>     rvec, _ = cv2.Rodrigues(R)
>     return rvec.ravel()
>
>
> K_t = torch.tensor(K)
>
>
> def project(w, t, X, cam_idx, pt_idx):
>     Xc = (rodrigues(w[cam_idx]) @ X[pt_idx][..., None])[..., 0] + t[cam_idx]
>     uv = (K_t @ (Xc / Xc[:, 2:]).T).T[:, :2]
>     return uv, Xc[:, 2]
>
>
> def bundle_adjust(poses, points, obs, iters=200, huber=2.0):
>     # poses: list of (R, t); points: (N, 3); obs: arrays cam, pt, uv
>     w = torch.tensor(np.array([rotmat_to_axis_angle(R) for R, _ in poses]), requires_grad=True)
>     t = torch.tensor(np.array([tv for _, tv in poses]), requires_grad=True)
>     X = torch.tensor(points, requires_grad=True)
>     cam_i, pt_i, uv = torch.tensor(obs["cam"]), torch.tensor(obs["pt"]), torch.tensor(obs["uv"])
>     fixed = torch.ones(len(poses), 1)
>     fixed[0] = 0.0  # the first camera does not move
>     opt = torch.optim.LBFGS([w, t, X], lr=1.0, max_iter=iters, line_search_fn="strong_wolfe")
>
>     def closure():
>         opt.zero_grad()
>         w_eff = w * fixed + w.detach() * (1 - fixed)
>         t_eff = t * fixed + t.detach() * (1 - fixed)
>         pred, _ = project(w_eff, t_eff, X, cam_i, pt_i)
>         r = torch.linalg.norm(pred - uv, dim=1)
>         loss = torch.where(r < huber, 0.5 * r ** 2, huber * (r - 0.5 * huber)).sum()
>         loss.backward()
>         return loss
>
>     opt.step(closure)
>     with torch.no_grad():
>         Rs = rodrigues(w).numpy()
>         new_poses = [(Rs[k], t[k].numpy().copy()) for k in range(len(poses))]
>         new_poses[0] = poses[0]
>         return new_poses, X.numpy().copy()
>
>
> def reprojection_errors(poses, points, obs):
>     w = torch.tensor(np.array([rotmat_to_axis_angle(R) for R, _ in poses]))
>     t = torch.tensor(np.array([tv for _, tv in poses]))
>     pred, depth = project(w, t, torch.tensor(points), torch.tensor(obs["cam"]), torch.tensor(obs["pt"]))
>     return torch.linalg.norm(pred - torch.tensor(obs["uv"]), dim=1).numpy(), depth.numpy()
> ```

### Two-view initialization

The reconstruction starts from views 0 and 2. Each inlier match becomes a 3D point with two observations, and every observation remembers which keypoint it came from, so later views can find it. Points that triangulate behind a camera, or from rays that are almost parallel, are dropped: a small angle between the rays makes depth very uncertain.

> [accordion] Code
>
> ```python theme={null}
> def ray_angle_deg(X, C1, C2):
>     a, b = X - C1, X - C2
>     cosang = np.sum(a * b, 1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1))
>     return np.degrees(np.arccos(np.clip(cosang, -1, 1)))
>
>
> def center(R, t):
>     return -R.T @ t
>
>
> # reconstruction state
> view_ids = [0, 2]                      # image index of each registered camera
> poses = [(np.eye(3), np.zeros(3)), (R01, t01)]
> points = np.empty((0, 3))
> obs = {"cam": [], "pt": [], "uv": []}
> kp_to_pt = {}                          # (image index, keypoint index) -> point index
>
>
> def add_points(cam_a, cam_b, pairs, X):
>     global points
>     base = len(points)
>     points = np.vstack([points, X])
>     for k, (ia, ib) in enumerate(pairs):
>         for cam, img, kp in ((cam_a, view_ids[cam_a], ia), (cam_b, view_ids[cam_b], ib)):
>             obs["cam"].append(cam); obs["pt"].append(base + k); obs["uv"].append(kps[img][kp])
>             kp_to_pt[(img, kp)] = base + k
>
>
> def as_arrays(o):
>     return {k: np.array(v) for k, v in o.items()}
>
>
> X01 = triangulate(P0, np.hstack([R01, t01[:, None]]), x1[inl01], x2[inl01])
> keep = ((X01[:, 2] > 0) & ((X01 @ R01.T + t01)[:, 2] > 0)
>         & (ray_angle_deg(X01, center(*poses[0]), center(*poses[1])) > 1.0))
> add_points(0, 1, m01[inl01][keep], X01[keep])
>
> err, _ = reprojection_errors(poses, points, as_arrays(obs))
> print(f"{len(points)} points; median reprojection error before bundle adjustment: {np.median(err):.2f} px")
> poses, points = bundle_adjust(poses, points, as_arrays(obs))
> err, _ = reprojection_errors(poses, points, as_arrays(obs))
> print(f"median reprojection error after bundle adjustment: {np.median(err):.2f} px")
> ```

```output theme={null}
281 points; median reprojection error before bundle adjustment: 0.26 px
median reprojection error after bundle adjustment: 0.08 px
```

### Adding views

Each new photo is registered against the points you already have. Match it to the registered views, and every match whose keypoint already belongs to a 3D point gives a 2D-to-3D correspondence. Finding a camera pose from such correspondences is the *perspective-n-point* problem (PnP). RANSAC again separates good correspondences from bad ones. Then the matches that do not yet have a point are triangulated against the registered view they match, which adds new points, and bundle adjustment refines all poses and points together. This is *incremental* structure from motion, the strategy COLMAP uses. *Global* methods instead estimate all rotations and translations at once from the pairwise relative poses and refine them afterwards (Pan et al., 2024).

After each bundle adjustment, observations with a reprojection error above four pixels are removed, so wrong matches that survived RANSAC do not accumulate.

> [accordion] Code
>
> ```python theme={null}
> def prune(max_err=4.0):
>     global obs
>     o = as_arrays(obs)
>     err, depth = reprojection_errors(poses, points, o)
>     good = (err < max_err) & (depth > 0)
>     obs = {k: list(v[good]) for k, v in o.items()}
>     for (img, kp), p in list(kp_to_pt.items()):
>         cam = view_ids.index(img)
>         if not np.any((o["cam"][good] == cam) & (o["pt"][good] == p)):
>             del kp_to_pt[(img, kp)]
>     return int((~good).sum())
>
>
> history = []
> order = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]
> for new in order:
>     # 2D-3D correspondences from matches with the last three registered views
>     obj, img_pts, seen = [], [], set()
>     match_cache = {}
>     for img in view_ids[-3:]:
>         pairs = match(new, img)
>         match_cache[img] = pairs
>         for a, b in pairs:
>             p = kp_to_pt.get((img, b))
>             if p is not None and a not in seen:
>                 seen.add(a); obj.append(points[p]); img_pts.append(kps[new][a])
>     ok, rvec, tvec, inl = cv2.solvePnPRansac(
>         np.array(obj), np.array(img_pts), K, None, reprojectionError=3.0,
>         iterationsCount=2000, flags=cv2.SOLVEPNP_EPNP)
>     R_new = cv2.Rodrigues(rvec)[0]
>     t_new = tvec.ravel()
>     view_ids.append(new); poses.append((R_new, t_new))
>     cam_new = len(poses) - 1
>     # observations of existing points in the new view
>     for img, pairs in match_cache.items():
>         for a, b in pairs:
>             p = kp_to_pt.get((img, b))
>             if p is not None and (new, a) not in kp_to_pt:
>                 obs["cam"].append(cam_new); obs["pt"].append(p); obs["uv"].append(kps[new][a])
>                 kp_to_pt[(new, a)] = p
>     # new points from matches with the most recent registered views
>     n_before = len(points)
>     for img, pairs in match_cache.items():
>         fresh = np.array([(a, b) for a, b in pairs
>                           if (new, a) not in kp_to_pt and (img, b) not in kp_to_pt], dtype=int)
>         if len(fresh) < 8:
>             continue
>         cam_old = view_ids.index(img)
>         Ro, to = poses[cam_old]
>         xa, xb = to_normalized(kps[new][fresh[:, 0]]), to_normalized(kps[img][fresh[:, 1]])
>         Xn = triangulate(np.hstack([R_new, t_new[:, None]]), np.hstack([Ro, to[:, None]]), xa, xb)
>         good = (((Xn @ R_new.T + t_new)[:, 2] > 0) & ((Xn @ Ro.T + to)[:, 2] > 0)
>                 & (ray_angle_deg(Xn, center(R_new, t_new), center(Ro, to)) > 1.0))
>         # keep only points that reproject well in both views
>         tmp = {"cam": np.r_[np.full(good.sum(), cam_new), np.full(good.sum(), cam_old)],
>                "pt": np.r_[np.arange(good.sum()), np.arange(good.sum())],
>                "uv": np.vstack([kps[new][fresh[good, 0]], kps[img][fresh[good, 1]]])}
>         e, _ = reprojection_errors(poses, Xn[good], tmp)
>         ok_pts = (e.reshape(2, -1) < 3.0).all(0)
>         add_points(cam_new, cam_old, fresh[good][ok_pts], Xn[good][ok_pts])
>     poses, points = bundle_adjust(poses, points, as_arrays(obs))
>     removed = prune()
>     err, _ = reprojection_errors(poses, points, as_arrays(obs))
>     history.append((new, len(inl), len(points) - n_before, len(points), np.median(err)))
>     print(f"view {new}: PnP inliers {len(inl):4d}, new points {len(points) - n_before:5d}, "
>           f"total points {len(points):5d}, removed observations {removed:4d}, "
>           f"median error {np.median(err):.2f} px")
> ```

```output theme={null}
view 1: PnP inliers  186, new points  1152, total points  1433, removed observations   12, median error 0.08 px
view 3: PnP inliers  310, new points   534, total points  1967, removed observations   62, median error 0.13 px
view 4: PnP inliers  433, new points   665, total points  2632, removed observations   74, median error 0.14 px
view 5: PnP inliers  474, new points   500, total points  3132, removed observations   69, median error 0.14 px
view 6: PnP inliers  352, new points   407, total points  3539, removed observations   37, median error 0.13 px
view 7: PnP inliers  316, new points   419, total points  3958, removed observations   66, median error 0.14 px
view 8: PnP inliers  286, new points   515, total points  4473, removed observations   70, median error 0.14 px
view 9: PnP inliers  307, new points   572, total points  5045, removed observations   57, median error 0.14 px
view 10: PnP inliers  375, new points   676, total points  5721, removed observations   45, median error 0.14 px
view 11: PnP inliers  542, new points   564, total points  6285, removed observations   45, median error 0.14 px
```

Every new view registers with hundreds of PnP inliers, and the median reprojection error stays well below a pixel. The reconstruction keeps the scale fixed by the first pair. With a long sequence and no loop closure, small errors in each new pose add up, which is called *drift*; twelve photos on a short arc are too few for it to show.

## Comparison with COLMAP

The dataset's authors reconstructed all 185 photos with COLMAP, which runs the same pipeline in a more careful form (Schonberger2016-xn). Its poses serve as the reference here. [Structure from Motion at Scale](https://aegean.ai/aiml-common/lectures/3d-reconstruction/colmap/index.md) runs COLMAP itself on these twelve photos and lines up each of its stages with the steps above.

Your reconstruction and COLMAP's live in different gauges, with different origin, orientation and scale. To compare them you find the similarity transform $\mathbf{y} \approx s R \mathbf{x} + \mathbf{t}$ that best maps your camera centers $\mathbf{x}_k$ onto COLMAP's centers $\mathbf{y}_k$. The least-squares solution has a closed form (the Umeyama method). Center both sets, take the SVD of their cross-covariance $\Sigma_{xy} = U D V^{\top}$, and set

$$
\begin{aligned}
R &= U S V^{\top}, \\
s &= \operatorname{tr}(D S) / \sigma_x^2, \\
\mathbf{t} &= \bar{\mathbf{y}} - s R \bar{\mathbf{x}},
\end{aligned}
$$

where $S = \operatorname{diag}(1, 1, \pm 1)$ makes $\det R = +1$, and $\sigma_x^2$ is the mean squared distance of the $\mathbf{x}_k$ from their centroid.

> [accordion] Code
>
> ```python theme={null}
> def umeyama(x, y):
>     mx, my = x.mean(0), y.mean(0)
>     xc, yc = x - mx, y - my
>     U, D, Vt = np.linalg.svd(yc.T @ xc / len(x))
>     S = np.diag([1.0, 1.0, np.sign(np.linalg.det(U @ Vt))])
>     R = U @ S @ Vt
>     s = np.trace(np.diag(D) @ S) / xc.var(0).sum()
>     return s, R, my - s * R @ mx
>
>
> ours_C = np.array([center(*poses[view_ids.index(v)]) for v in range(len(VIEW_NAMES))])
> ref = [colmap_images[n] for n in VIEW_NAMES]
> ref_C = np.array([center(r["R"], r["t"]) for r in ref])
> s, R_al, t_al = umeyama(ours_C, ref_C)
> aligned_C = (s * (R_al @ ours_C.T)).T + t_al
> pos_err = np.linalg.norm(aligned_C - ref_C, axis=1)
> span = np.linalg.norm(ref_C[-1] - ref_C[0])
> rot_err = []
> for v, r in enumerate(ref):
>     R_ours = poses[view_ids.index(v)][0] @ R_al.T   # world-to-camera, in COLMAP's frame
>     c = (np.trace(R_ours @ r["R"].T) - 1) / 2
>     rot_err.append(np.degrees(np.arccos(np.clip(c, -1, 1))))
> print(f"camera position error after alignment: RMS {np.sqrt(np.mean(pos_err**2)):.4f}, "
>       f"max {pos_err.max():.4f} (COLMAP units)")
> print(f"the cameras span {span:.3f} units, so the RMS error is "
>       f"{100 * np.sqrt(np.mean(pos_err**2)) / span:.2f}% of the span")
> print(f"camera orientation error: mean {np.mean(rot_err):.3f} deg, max {np.max(rot_err):.3f} deg")
> # relative rotations between consecutive cameras do not depend on the gauge
> rel_err = []
> for v in range(len(ref) - 1):
>     Ra, Rb = poses[view_ids.index(v)][0], poses[view_ids.index(v + 1)][0]
>     D = (Rb @ Ra.T) @ (ref[v + 1]["R"] @ ref[v]["R"].T).T
>     rel_err.append(np.degrees(np.arccos(np.clip((np.trace(D) - 1) / 2, -1, 1))))
> print(f"relative rotation between consecutive cameras: mean error {np.mean(rel_err):.3f} deg")
> ```

```output theme={null}
camera position error after alignment: RMS 0.0129, max 0.0200 (COLMAP units)
the cameras span 7.294 units, so the RMS error is 0.18% of the span
camera orientation error: mean 0.904 deg, max 0.965 deg
relative rotation between consecutive cameras: mean error 0.047 deg
```

![Left, a top view of the garden reconstruction: gray COLMAP points form the table and the surrounding garden, blue points of your reconstruction cover the same table region, and the 185 COLMAP camera centers form an ellipse around the table with your twelve cameras on a short arc of it. Right, a close-up of the twelve camera centers, where your aligned centers sit on top of COLMAP's.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/structure-from-motion/images/cell_14_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=bcfccbc6c08f7517c2f83fcb2a592223)

After the similarity alignment your twelve cameras sit on COLMAP's. The position error is a small fraction of a percent of the distance the cameras moved. Your points are far sparser than COLMAP's, because twelve photos at one eighth of the resolution see much less, but they lie where COLMAP's points lie. The two pipelines agree although yours used twelve photos and COLMAP used all 185.

The orientation error of each camera is under a degree and almost the same for every camera. That shared part comes from the alignment, not from the cameras: the twelve centers lie close to one arc, which pins down the rotation of the similarity transform less tightly than the cameras pin down each other. The rotation between consecutive cameras does not depend on the alignment, and there your reconstruction and COLMAP's agree to a few hundredths of a degree.

## What the reconstruction hands on

The three files are the output of structure from motion, and [Structure from Motion at Scale](https://aegean.ai/aiml-common/lectures/3d-reconstruction/colmap/index.md#output-files-and-conventions) describes their format and conventions. They are also the input of the two radiance field methods in this chapter:

* `cameras.bin`: the intrinsics $K$ of each camera model.
* `images.bin`: for every photo, its rotation (as a quaternion) and translation, plus the keypoints it contributed.
* `points3D.bin`: the sparse points, each with a color, a mean reprojection error and the list of photos that saw it.

> [accordion] Code
>
> ```python theme={null}
> print(f"cameras.bin   {len(cameras)} camera model, {cam['width']} x {cam['height']} pixels, "
>       f"fx = {fx:.1f}, fy = {fy:.1f}, cx = {cx:.1f}, cy = {cy:.1f}")
> print(f"images.bin    {len(colmap_images)} poses; for example {names[0]}:")
> print("              R =", np.array2string(colmap_images[names[0]]["R"], precision=3).replace("\n", "\n                  "))
> print("              t =", colmap_images[names[0]]["t"].round(3))
> print(f"points3D.bin  {len(colmap_xyz)} points, median reprojection error {np.median(colmap_err):.2f} px")
> ```

```output theme={null}
cameras.bin   1 camera model, 5187 x 3361 pixels, fx = 3844.9, fy = 3852.4, cx = 2593.5, cy = 1680.5
images.bin    185 poses; for example DSC07956.JPG:
              R = [[ 1.     0.009  0.007]
                   [-0.011  0.957  0.291]
                   [-0.004 -0.291  0.957]]
              t = [-0.328 -1.926  3.958]
points3D.bin  138766 points, median reprojection error 1.17 px
```

[Neural Radiance Fields](https://aegean.ai/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/index.md) and [Gaussian Splatting](https://aegean.ai/aiml-common/lectures/3d-reconstruction/gaussian-splatting/index.md) both read these files for the same garden scene. Both use the poses to turn each pixel into a ray in the scene. Gaussian splatting also uses the sparse points: it places one Gaussian at each of them as its starting scene, and the optimization grows the rest.

## References

* Hartley, R., Zisserman, A. (2004). *Multiple View Geometry in Computer Vision*.
* Pan, L., Baráth, D., Pollefeys, M., Schönberger, J. (2024). *Global Structure-from-Motion Revisited*. arXiv \[cs.CV]. [Link](http://arxiv.org/abs/2407.20219)
* Triggs, B., Mc Lauchlan, P., Hartley, R., Fitzgibbon, A. (2000). *Bundle Adjustment — A Modern Synthesis*. Plan. Perspect. [Link](http://www.cs.jhu.edu/~misha/ReadingSeminar/Papers/Triggs00.pdf)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/3d-reconstruction/structure-from-motion).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.