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

# Structure from Motion at Scale

> The incremental pipeline as a robust, widely used system.

[![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/colmap/index.ipynb)

[Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md) builds incremental structure from motion by hand: features and matches, the essential matrix, triangulation, then one view at a time with PnP and bundle adjustment. COLMAP is the system most reconstructions in research and practice come from. It is not a different method. It runs the same incremental pipeline, with far more care at every stage about what can go wrong (Schonberger2016-xn).

In this section you run COLMAP on the same twelve photos, line up each of its stages with the step you built, and compare the result with the reference reconstruction. You then see how the choice of which image pairs to match changes the cost, how cameras are shared between photos, and what the output files mean. [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 start from these files.

## The same pipeline, engineered

Every stage of COLMAP corresponds to a step of [Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md). The table lines them up.

| COLMAP stage | What it does | The step you built |
| - | - | - |
| Feature extraction | SIFT keypoints and descriptors in every photo | Features and matches |
| Matching | Nearest-neighbor descriptor matches with a ratio test, for each chosen pair of photos | Features and matches |
| Geometric verification | RANSAC fits an essential, fundamental or homography matrix to each pair and keeps the inliers | Estimating E with RANSAC |
| Initial pair | Chooses two photos with many inliers and a wide baseline to start from | Two-view initialization |
| Next view | Picks the unregistered photo that sees the most already reconstructed points, spread across the image, and finds its pose with PnP and RANSAC | Adding views |
| Triangulation | Creates new points from tracks across all registered photos, rejecting low triangulation angles | Relative pose and triangulation |
| Bundle adjustment | Local adjustment around each new photo, global adjustment of the whole model at intervals | Reprojection error and bundle adjustment |
| Filtering and retriangulation | Removes points with large reprojection error, then retries triangulation of tracks that failed | Pruning above a pixel threshold |
| Camera refinement | Optimizes focal length, principal point and lens distortion together with the poses | Not done: you used the known intrinsics |

The differences are in scale and robustness. COLMAP matches thousands of photos, scores which view to add next instead of taking the next one in order, triangulates each point from its whole track of photos, and keeps adjusting the intrinsics. You fixed the intrinsics to the reference values. COLMAP estimates them from the photos alone, which is what you need for a phone or camera you have never calibrated.

Genuinely different approaches to the same problem exist. Global structure from motion, such as GLOMAP, estimates all camera rotations at once and then all positions, instead of growing the model one view at a time (Pan et al., 2024). Learned methods such as [VGGT](https://arxiv.org/abs/2503.11651) and [MASt3R-SfM](https://arxiv.org/abs/2409.19152) predict camera poses and dense geometry directly from the photos with a network, and often feed the result to bundle adjustment.

> [accordion] Code
>
> ```python theme={null}
> import os
> import shutil
> import subprocess
> import sys
> import time
> import warnings
> from pathlib import Path
>
> warnings.filterwarnings("ignore")
> os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
>
> try:
>     import pycolmap
> except ImportError:
>     try:
>         subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "pycolmap==4.2.1"])
>     except Exception:
>         subprocess.check_call(["uv", "pip", "install", "-q", "--python", sys.executable, "pycolmap==4.2.1"])
>     import pycolmap
>
> import matplotlib.pyplot as plt
> import numpy as np
> 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",
> })
> pycolmap.logging.minloglevel = 2 if hasattr(pycolmap, "logging") else None
> ```

## The scene and the reference model

The photos are the *garden* scene of the Mip-NeRF 360 dataset, 185 photos taken while walking around a table, here at one eighth of their size. The dataset ships with a COLMAP reconstruction of all 185 photos, made by the dataset's authors from the full-size images. Nobody reran it here. It serves as the reference that both your own reconstruction and the run below are compared with.

> [accordion] Code
>
> ```python theme={null}
> DATA = Path(snapshot_download(
>     "mileleap/mipnerf360", repo_type="dataset",
>     allow_patterns=["garden/images_8/*", "garden/sparse/*"],
> )) / "garden"
> names = sorted(p.name for p in (DATA / "images_8").iterdir())
> ref = pycolmap.Reconstruction(str(DATA / "sparse" / "0"))
> ref_cam = next(iter(ref.cameras.values()))
> print(f"reference: {ref.num_reg_images()} photos, {ref.num_points3D()} points, "
>       f"mean reprojection error {ref.compute_mean_reprojection_error():.2f} px")
> print(f"reference camera: {ref_cam.model.name}, {ref_cam.width} x {ref_cam.height}, "
>       f"params {np.round(ref_cam.params, 4).tolist()}")
> ```

```output theme={null}
reference: 185 photos, 138766 points, mean reprojection error 1.20 px
reference camera: PINHOLE, 5187 x 3361, params [3844.8988, 3852.3562, 2593.5, 1680.5]
```

## Running COLMAP on twelve photos

The run uses photos 21 to 32 in name order, the same twelve as [Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md). It has three stages. Feature extraction finds up to 8192 SIFT features per photo, with affine-adapted shapes and descriptors pooled over several scales, which makes matches more reliable under changes of viewpoint. Matching compares every pair of photos, keeps a match only if it passes the ratio test at 0.8 and is the mutual nearest neighbor in both directions, then verifies each pair geometrically. Mapping grows the reconstruction. It discards points whose reprojection error exceeds 4 pixels and refines the focal length, the principal point and one radial distortion coefficient together with the poses.

All twelve photos share one camera, because one camera took them all. The model is *simple radial*: one focal length, a principal point and one distortion coefficient. Unlike your reconstruction, this run is not told the intrinsics.

> [accordion] Code
>
> ```python theme={null}
> WORK = Path("colmap_runs")
> shutil.rmtree(WORK, ignore_errors=True)
>
>
> def run_colmap(view_names, tag, pairing="exhaustive", overlap=10):
>     w = WORK / tag
>     (w / "images").mkdir(parents=True)
>     for n in view_names:
>         shutil.copy(DATA / "images_8" / n, w / "images" / n)
>     db = w / "database.db"
>
>     extraction = pycolmap.FeatureExtractionOptions()
>     extraction.use_gpu = False
>     extraction.sift.max_num_features = 8192
>     extraction.sift.estimate_affine_shape = True
>     extraction.sift.domain_size_pooling = True
>     reader = pycolmap.ImageReaderOptions()
>     reader.camera_model = "SIMPLE_RADIAL"
>     t0 = time.time()
>     pycolmap.extract_features(db, w / "images", camera_mode=pycolmap.CameraMode.SINGLE,
>                               reader_options=reader, extraction_options=extraction,
>                               device=pycolmap.Device.cpu)
>     t_extract = time.time() - t0
>
>     matching = pycolmap.FeatureMatchingOptions()
>     matching.use_gpu = False
>     matching.sift.max_ratio = 0.8
>     matching.sift.cross_check = True
>     t0 = time.time()
>     if pairing == "exhaustive":
>         pycolmap.match_exhaustive(db, matching_options=matching, device=pycolmap.Device.cpu)
>     else:
>         seq = pycolmap.SequentialPairingOptions()
>         seq.overlap = overlap
>         seq.quadratic_overlap = False
>         pycolmap.match_sequential(db, matching_options=matching, pairing_options=seq,
>                                   device=pycolmap.Device.cpu)
>     t_match = time.time() - t0
>     database = pycolmap.Database.open(str(db))
>     pairs_tried = database.num_matched_image_pairs()
>     inliers = np.array(database.read_two_view_geometry_num_inliers()[1])
>     database.close()
>
>     mapping = pycolmap.IncrementalPipelineOptions()
>     mapping.min_num_matches = 15
>     mapping.ba_refine_focal_length = True
>     mapping.ba_refine_principal_point = True
>     mapping.ba_refine_extra_params = True
>     mapping.mapper.filter_max_reproj_error = 4.0
>     mapping.random_seed = 0
>     (w / "sparse").mkdir()
>     t0 = time.time()
>     models = pycolmap.incremental_mapping(db, w / "images", w / "sparse", options=mapping)
>     t_map = time.time() - t0
>     rec = max(models.values(), key=lambda r: r.num_reg_images())
>     stats = dict(pairs_tried=pairs_tried, pairs_verified=int((inliers >= 15).sum()),
>                  t_extract=t_extract, t_match=t_match, t_map=t_map)
>     return rec, stats
>
>
> VIEW_NAMES = names[20:32]
> rec12, st12 = run_colmap(VIEW_NAMES, "twelve")
> cam12 = next(iter(rec12.cameras.values()))
> print(f"registered photos   {rec12.num_reg_images()} of {len(VIEW_NAMES)}")
> print(f"3D points           {rec12.num_points3D()}")
> print(f"mean track length   {rec12.compute_mean_track_length():.2f} photos")
> print(f"mean reproj. error  {rec12.compute_mean_reprojection_error():.3f} px")
> print(f"time                {st12['t_extract'] + st12['t_match'] + st12['t_map']:.1f} s")
> ```

```output theme={null}
registered photos   12 of 12
3D points           2983
mean track length   3.73 photos
mean reproj. error  0.269 px
time                4.6 s
```

## Comparison with the reference

COLMAP's twelve cameras live in their own gauge, so the comparison first finds the similarity transform that maps their centers onto the reference centers of the same twelve photos (the Umeyama method). It then compares positions, orientations and the estimated camera.

> [accordion] Code
>
> ```python theme={null}
> def center(img):
>     return img.projection_center()
>
>
> def rotation(img):
>     return img.cam_from_world().rotation.matrix()
>
>
> 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.eye(3)
>     if np.linalg.det(U) * np.linalg.det(Vt) < 0:
>         S[2, 2] = -1
>     R = U @ S @ Vt
>     s = np.trace(np.diag(D) @ S) / xc.var(0).sum()
>     return s, R, my - s * R @ mx
>
>
> by_name12 = {img.name: img for img in rec12.images.values()}
> by_name_ref = {img.name: img for img in ref.images.values()}
> X = np.array([center(by_name12[n]) for n in VIEW_NAMES])
> Y = np.array([center(by_name_ref[n]) for n in VIEW_NAMES])
> s, R_al, t_al = umeyama(X, Y)
> X_al = (s * (R_al @ X.T)).T + t_al
> err = np.linalg.norm(X_al - Y, axis=1)
> span = np.linalg.norm(Y.max(0) - Y.min(0))
>
>
> def angle(Ra, Rb):
>     return np.degrees(np.arccos(np.clip((np.trace(Ra.T @ Rb) - 1) / 2, -1, 1)))
>
>
> rel = [angle(rotation(by_name12[a]) @ rotation(by_name12[b]).T,
>              rotation(by_name_ref[a]) @ rotation(by_name_ref[b]).T)
>        for a, b in zip(VIEW_NAMES[:-1], VIEW_NAMES[1:])]
> f_ref = ref_cam.params[0] * cam12.width / ref_cam.width
> print(f"position error      RMS {np.sqrt((err**2).mean()):.4f}, max {err.max():.4f} reference units")
> print(f"                    {100 * np.sqrt((err**2).mean()) / span:.2f}% of the {span:.3f}-unit span of these cameras")
> print(f"relative rotation   mean difference {np.mean(rel):.3f} deg between consecutive cameras")
> print(f"focal length        {cam12.params[0]:.1f} px estimated, {f_ref:.1f} px reference (scaled)")
> print(f"distortion k        {cam12.params[3]:.4f} estimated; the reference {ref_cam.model.name} camera has no distortion term")
> ```

```output theme={null}
position error      RMS 0.0048, max 0.0076 reference units
                    0.06% of the 7.525-unit span of these cameras
relative rotation   mean difference 0.053 deg between consecutive cameras
focal length        483.3 px estimated, 480.3 px reference (scaled)
distortion k        0.0032 estimated; the reference PINHOLE camera has no distortion term
```

![Output from cell 5](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/colmap/images/cell_5_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=d3bdbc5465be2daedef4c0ab2d63c5f7)

COLMAP registers all twelve photos with a mean reprojection error of about a quarter of a pixel. After the alignment its camera centers lie within 0.06% of the span of these cameras from the reference, about a third of the 0.18% that your own reconstruction reached in [Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md). It got there without being told the intrinsics: its focal length comes out within 1% of the reference value scaled to these photos. The reference camera is a pinhole with no distortion term, and the distortion coefficient COLMAP estimated is close to zero.

The rotation between consecutive cameras agrees with the reference to under a tenth of a degree. That is slightly worse than the 0.047° of your reconstruction, which used the reference intrinsics exactly. Estimating the camera from twelve photos costs a little accuracy in orientation, and buys independence from any calibration.

## Choosing which pairs to match

Matching is usually the most expensive stage, because the number of candidate pairs grows quickly with the number of photos. COLMAP offers several ways to choose the pairs:

* *Exhaustive* matching tries every pair, $n(n-1)/2$ of them. It suits unordered photo sets of up to a few hundred images, because it cannot miss an overlap.
* *Sequential* matching tries each photo only against the next $k$ in capture order, about $nk$ pairs. It suits video and walk-around captures, where neighbors in time are neighbors in space. A loop-detection option adds pairs that a visual vocabulary flags as similar, so that returning to the starting point closes the loop.
* *Vocabulary tree* matching retrieves the most similar photos for each photo, for very large unordered sets.
* *Spatial* matching pairs photos whose GPS or other position priors are close.

The run below compares exhaustive and sequential matching ($k = 10$) on the first 60 photos of the walk.

> [accordion] Code
>
> ```python theme={null}
> rec_e, st_e = run_colmap(names[:60], "exhaustive60", pairing="exhaustive")
> rec_s, st_s = run_colmap(names[:60], "sequential60", pairing="sequential", overlap=10)
> print(f"{'':22s}{'exhaustive':>12s}{'sequential':>12s}")
> rows = [
>     ("pairs tried", st_e["pairs_tried"], st_s["pairs_tried"], "d"),
>     ("pairs verified", st_e["pairs_verified"], st_s["pairs_verified"], "d"),
>     ("matching time (s)", st_e["t_match"], st_s["t_match"], ".1f"),
>     ("mapping time (s)", st_e["t_map"], st_s["t_map"], ".1f"),
>     ("registered photos", rec_e.num_reg_images(), rec_s.num_reg_images(), "d"),
>     ("3D points", rec_e.num_points3D(), rec_s.num_points3D(), "d"),
>     ("mean track length", rec_e.compute_mean_track_length(), rec_s.compute_mean_track_length(), ".2f"),
>     ("mean reproj. error", rec_e.compute_mean_reprojection_error(), rec_s.compute_mean_reprojection_error(), ".3f"),
> ]
> for label, a, b, f in rows:
>     print(f"{label:22s}{a:>12{f}}{b:>12{f}}")
> ```

```output theme={null}
                        exhaustive  sequential
pairs tried                   1770         545
pairs verified                 681         351
matching time (s)              6.6         5.6
mapping time (s)              16.5        11.4
registered photos               60          60
3D points                    18519       15695
mean track length             5.04        4.05
mean reproj. error           0.384       0.319
```

Sequential matching tried 545 pairs instead of 1770, under a third, and still registered all 60 photos. It verified fewer pairs, so tracks are shorter and the model has fewer points: each point is seen in about four photos instead of five. The time saved is a few seconds at this size. Exhaustive matching grows with the square of the number of photos, though, so for thousands of photos only sequential or retrieval-based matching is practical. The 60 photos cover only part of the walk around the table, so closing the loop does not come up here.

## Cameras for your own photos

COLMAP describes each physical camera by a model and its parameters. The common models are:

| Model | Parameters | Use |
| - | - | - |
| `SIMPLE_PINHOLE` | $f, c_x, c_y$ | Synthetic renders, undistorted images |
| `PINHOLE` | $f_x, f_y, c_x, c_y$ | Undistorted images with non-square pixels |
| `SIMPLE_RADIAL` | $f, c_x, c_y, k$ | Phone photos and most consumer cameras |
| `OPENCV` | $f_x, f_y, c_x, c_y, k_1, k_2, p_1, p_2$ | Wide-angle lenses with stronger distortion |

How cameras are shared between photos matters as much as the model. There are three choices. One camera for all photos is right when one device with fixed zoom and focus took them all; it gives bundle adjustment the most observations per intrinsic parameter. One camera per photo is right only when every photo really comes from a different device or zoom setting, because each photo then has to pin down its own intrinsics. One camera per source, such as one for the still photos and one for each video resolution, is right for a capture that mixes devices or image sizes.

A mixed capture needs one camera per source because a single shared camera cannot describe images of different sizes, and photos that do not fit the shared camera fail to register. Giving every photo its own camera registers them, but the many separate intrinsics are poorly constrained and slow down whatever reads the model next.

Never rewrite the intrinsics after bundle adjustment, for example by merging many refined cameras into a few afterwards. Bundle adjustment optimized every pose jointly with the intrinsics it had at the time. Swapping in different intrinsics leaves each pose wrong for its new camera, and the error shows up later as blurry reconstructions and poor results on held-out views. Decide the sharing before reconstruction, and let bundle adjustment refine the shared cameras.

A few capture rules make reconstruction work the first time:

* Lock exposure and focus, so that the same surface has the same brightness in every photo.
* Overlap neighboring photos by about 70%, so that every point appears in several of them.
* Walk several loops at different heights around the subject, so that triangulation angles are large and the whole object is seen.
* Keep the scene still. Anything that moves between photos breaks the assumption that one 3D point explains all of its observations.

## Output files and conventions

A reconstruction is three files, written in binary (`.bin`) or text (`.txt`) form with the same content. `cameras` holds one line per camera: its model, image size and parameters. `images` holds two lines per photo: the pose and camera of the photo, then the 2D keypoints with the ID of the 3D point each one observes. `points3D` holds one line per point: its position, color, mean reprojection error and the track of photos that see it.

> [accordion] Code
>
> ```python theme={null}
> TXT = WORK / "twelve_txt"
> TXT.mkdir(exist_ok=True)
> rec12.write_text(str(TXT))
> for fname, n_lines in [("cameras.txt", 4), ("images.txt", 6), ("points3D.txt", 4)]:
>     print(f"--- {fname}")
>     for line in (TXT / fname).read_text().splitlines()[:n_lines]:
>         print(line if len(line) <= 110 else line[:107] + "...")
> ```

```output theme={null}
--- cameras.txt
# Camera list with one line of data per camera:
#   CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]
# Number of cameras: 1
1 SIMPLE_RADIAL 648 420 483.29976543234295 323.740610276891 207.53383802653264 0.0032277184622809358
--- images.txt
# Image list with two lines of data per image:
#   IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME
#   POINTS2D[] as (X, Y, POINT3D_ID)
# Number of images: 12, mean observations per image: 927.58333333333337
2 0.99693058406653645 0.031114829968855822 -0.071698681316478649 0.004536188514814821 -2.2828676748725427 -...
232.85714721679688 223.34898376464844 -1 625.32720947265625 342.90826416015625 -1 625.32720947265625 342.90...
--- points3D.txt
# 3D point list with one line of data per point:
#   POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)
# Number of points: 2983, mean track length: 3.7314783774723432
1 2.1300144788576167 -1.554677629689059 19.748250504941765 14 21 4 0.89998482719640882 1 46 2 93 9 93 12 53
```

The pose stored for each photo is world-to-camera. A quaternion $(q_w, q_x, q_y, q_z)$ gives the rotation $R$ and the three numbers after it give the translation $\mathbf{t}$, so a world point $\mathbf{X}$ lands at $R\mathbf{X} + \mathbf{t}$ in camera coordinates, with $x$ to the right, $y$ down and $z$ forward. The camera center in the world is the point that maps to the origin:

$$
\mathbf{o} = -R^{\top}\mathbf{t}.
$$

Readers that expect camera-to-world poses, as the renderers of the radiance field sections do, invert this.

> [accordion] Code
>
> ```python theme={null}
> img = by_name12[VIEW_NAMES[0]]
> T = img.cam_from_world()
> R, t = T.rotation.matrix(), T.translation
> print("R X + t for the center:", np.round(R @ (-R.T @ t) + t, 12))
> print("-R^T t                :", np.round(-R.T @ t, 6))
> print("projection_center()   :", np.round(img.projection_center(), 6))
> ```

```output theme={null}
R X + t for the center: [ 0.  0. -0.]
-R^T t                : [ 5.796792  0.057388 -1.471526]
projection_center()   : [ 5.796792  0.057388 -1.471526]
```

The frame itself is arbitrary. As [Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md) showed, photos fix a reconstruction only up to a rotation, a translation and a scale, seven degrees of freedom in all. COLMAP puts the origin and orientation wherever its initial pair left them, and its unit of length is whatever that pair's baseline turned out to be. Any use that needs meters or a known *up* direction, such as placing a robot in the reconstruction, has to fix those seven numbers from outside information.

### Grounding the frame in world coordinates

COLMAP has its own steps for fixing the gauge from outside information.

| COLMAP step | Outside information | What it fixes |
| - | - | - |
| `model_aligner` | Camera positions for at least three photos: measured, from GPS converted to a local metric frame, or from another reconstruction | All seven degrees of freedom |
| `model_orientation_aligner` | None beyond the images: line vanishing points of a man-made scene, or the assumption that most photos were taken upright | The rotation only, with gravity along $+y$ because COLMAP's $y$ axis points down |
| `pose_prior_mapper` | GPS positions with an uncertainty, used while the model is built | Scale and placement during mapping, instead of afterwards |
| `model_transformer` | A similarity transform you computed elsewhere, for example from markers | Whatever that transform fixes |

Alignment to known camera positions is the same Umeyama similarity transform that the comparison above and [Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md) use, run inside RANSAC so that a few bad positions cannot pull it off. COLMAP reports the mean and median camera-center error after the fit. For a robot, the positions can be camera poses from the arm's forward kinematics, or markers measured in the robot's base frame, and the transform then moves every camera and point into robot coordinates. The steps differ in what they can recover. Gravity alone fixes the rotation and leaves scale and translation free. Metric scale needs at least one real distance or known positions. All seven degrees of freedom need at least three known positions that do not lie on a line. When the robot itself is in the scene, its own geometry can serve as the reference. [Registering a Scan to the Robot](https://aegean.ai/aiml-common/lectures/sim2real/frame-alignment/index.md) covers that case and how published real-to-sim systems handle it.

The cell below aligns the twelve-photo model to the reference camera positions in the same robust way. The reference plays the part of the outside measurements.

> [accordion] Code
>
> ```python theme={null}
> ransac = pycolmap.RANSACOptions()
> ransac.max_error = 0.02 * span
> sim = pycolmap.align_reconstruction_to_locations(rec12, VIEW_NAMES, Y, 3, ransac)
> M = sim.matrix()
> X_robust = (M[:, :3] @ X.T).T + M[:, 3]
> err_robust = np.linalg.norm(X_robust - Y, axis=1)
> print(f"scale               robust {sim.scale:.4f}, Umeyama {s:.4f}")
> print(f"rotation difference {angle(sim.rotation.matrix(), R_al):.4f} deg")
> print(f"position RMS        robust {np.sqrt((err_robust**2).mean()):.4f}, Umeyama {np.sqrt((err**2).mean()):.4f} reference units")
> ```

```output theme={null}
scale               robust 0.6358, Umeyama 0.6358
rotation difference 0.0000 deg
position RMS        robust 0.0048, Umeyama 0.0048 reference units
```

[Neural Radiance Fields](https://aegean.ai/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/index.md) reads the poses and intrinsics from these files to cast rays. [Gaussian Splatting](https://aegean.ai/aiml-common/lectures/3d-reconstruction/gaussian-splatting/index.md) reads the same poses and starts its Gaussians at the points.

## References

* 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)

***

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/colmap).


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