Skip to content

Reconstruction — from photographs to a splat#

A 3D Gaussian splat is trained from posed images and a seed of world points. Three namespaces of capturegraph-recipes get a capture there. The package sits on the core library: cg (import capturegraph as cg) supplies the containers and captured types every stage reads and writes — cg.Array, cg.Image, cg.Pose, cg.PointCloud — and the memoized-call machinery, cg.pure_function; cgr (import capturegraph_recipes as cgr) adds the ten analysis-only types a sparse reconstruction needs — cgr.Reconstruction, cgr.Matches, cgr.Splat, … — and the stages themselves:

Namespace From To
cgr.sfm images (and whatever poses a sensor gave) a Reconstruction: solved cameras, sparse points, observations
cgr.depth images, and a LiDAR map to fit to a learned depth map per image, metric where it could be fitted
cgr.splats posed images and a seed a Splat

Every stage is memoized: a cg.pure_function, computed once per input and shared by every caller — a script, a notebook, or a page, the website folder the server builds from a value and hosts at its URL. The string in @cg.pure_function("sfm.match/1") is the stage's versioned identity: it names every cache entry, editing the body never changes it, and bumping the /1 is how a changed stage invalidates its results (the contract is under pure_function).

Every stage also logs what it found, so a page's build log reads as the record of what happened to its photographs. A stage on a cache miss opens a scope named after itself; a stage it calls that already ran says so in one line; its own result is one info line with the numbers as fields. Written to a file sink, one match reads:

match  identity=sfm.match/1  0.0s
  keypoints: cached
  keypoints: cached
  Matched  candidates=412  inliers=188
match  identity=sfm.match/1  done  0.4s

Below, "Log: Matched with candidates, inliers" names that line's message and fields; a count (Matching pairs, Training) is a progress entry, redrawn as it advances.

How the stages share work#

A stage that needs a derived value calls the stage that produces it, and that call is a cache hit:

@cg.pure_function("sfm.match/1")
def match(image_a: cg.Image, image_b: cg.Image) -> cgr.Matches:
    a = keypoints(image_a).arrays()   # a hit after the first call for this image
    b = keypoints(image_b).arrays()
    ...

tracks calls match per pair, triangulate and bundle_adjust call keypoints per frame, refined calls predict then fitted. No stage threads features through its signature, so no key conditions on features: change the matcher and only matching and what follows recompute; add a session and only its images are detected.

Two container facts carry the rest. cg.Array broadcasts attribute access, so for a dataset frames (an Array[PosedImage]) frames.image is its images as one array and frames.pose its poses — and a broadcast array hashes as the type the stage's parameter declares, so frames.pose is exactly the Array[Pose] that nearby_pairs takes. A lookup that fails yields cg.Missing instead of raising — model.cameras["00017"] for an unregistered image, a session's panorama before it was captured — and a stage given Missing anywhere in its arguments returns Missing without running, which is how absence chains through a pipeline; cg.is_missing tests for it.

Cache-key rules#

The stages are memoized on their arguments, so what you pass decides what recomputes:

  • Choose pairs from the prior frames, never the reposed ones. A re-posed array holds different poses, so nearby_pairs(reposed(...).pose) selects a different pair set, and tracks — keyed on the images and the Pairs value — runs again (the match calls for pairs already seen still hit). reposed copies each image unchanged, so tracks(frames.image, pairs) is indifferent to which array supplies the images.
  • Build cg.Array[cg.PointCloud]([...]), not a list. A plain list is accepted but hashes as a different argument, so merged gets a second key for the same seeds.
  • Call predict and refined per session, not per scene. They are keyed on the whole array, so a scene-wide call re-evaluates every old session when a new one arrives; concatenate the sessions' refined frames instead, as the ARKit pipeline does.
  • Anchor at a constant, never at a value another session could change.

The geometry stages#

Each stage is one call that ends in an info line naming its result; the long ones also open a progress count over their inputs. The world every reconstruction shares is metric, right-handed and y-up (ARKit's), and a cg.Pose is a camera-to-world transform in the OpenGL convention with intrinsics at the photograph's own size.

keypoints(image, max_dimension=1600) -> Keypoints. OpenCV SIFT on the grey image, downscaled to max_dimension on its longest side, the 8 192 strongest features kept with positions mapped back to the stored size; descriptors are RootSIFT (L1-normalised, square-rooted), colours sampled from the image. A Keypoints is one .npz of named arrays — xy, scale, angle, descriptors, color, width, height — read with .arrays() or .array("xy"), as is every array record below. Log: Detected keypoints with count, width, height.

Pairs. Matching costs a pair at a time, so choosing pairs is choosing the run time. exhaustive_pairs(count) compares everything; sequential_pairs(count, window=10) compares each image with the next window, as a video walks; nearby_pairs(poses, count=None, neighbors=32, max_distance_meters=50.0, max_angle_degrees=90.0) uses prior poses to compare each camera with its nearest neighbours that stand close and look the same way. poses is an Array[Pose], one per image, in which case count is ignored; or the sparse Map[String, Pose] that exif_priors returns, which requires count, the number of images, and pairs an image without a prior with the neighbors images on either side of it in index order. nearby_pairs is the one door over the memoized dense_pairs and sparse_pairs, which is the name a log shows. All three return a Pairs: one array ab of image index pairs. Log: Chose pairs with count and, for nearby, mean_neighbors.

match(image_a, image_b) -> Matches. Lowe's ratio test (0.8) in both directions, keeping mutual pairs; then a fundamental matrix fitted by MAGSAC (1 px) keeps the pairs consistent with one rigid scene, so no intrinsics are needed. Fewer than 8 candidates cannot be verified and fewer than 15 inliers is chance agreement; both give no matches. A Matches is one array ab of keypoint index pairs, the first column into image_a's keypoints and the second into image_b's. Log: Matched with candidates, inliers.

tracks(images, pairs) -> Tracks. Every pair is matched across the thread pool (pmap, shown as a Matching pairs count), the matches become edges between (image, keypoint) nodes, and a track is a connected component. A component holding two keypoints of one image contradicts itself and is dropped whole, as is one shorter than two. A Tracks is one row per keypoint in a track — track, image, keypoint — sorted by track. Log: Chained tracks with tracks, mean_length.

triangulate(frames, tracks) -> Reconstruction. Each track is solved by the N-view DLT from all of its views under the frames' poses (Reading keypoints counts the frames). A point survives when two views see it at least 1.5° apart, it lies in front of every camera, and its mean reprojection error over those views stays within 4 px; a point the DLT could not place counts as an angle rejection. The result's cameras are the frames' poses, keyed by index; a point's colour is the mean of its keypoints'. Log: Triangulated with points, rejected_angle, rejected_behind, rejected_reprojection, median_reprojection_px.

A Reconstruction is three fields: cameras, a Map[String, Pose] keyed by image index ("00017", the array's index_name), so an absent key is an unregistered image and reads as Missing; points, a cg.PointCloud; and observations, an Observations of one (point, image, keypoint) row per observation, tying each point to the keypoints it was triangulated from.

bundle_adjust(frames, model, position_sigma_meters=None, refine_intrinsics=False) -> Reconstruction. SciPy's sparse trust-region least squares over Rodrigues rotations, translations and points (focal length and principal point too with refine_intrinsics), each observation contributing its reprojection error under a pseudo-Huber loss (2 px scale) so a wrong match cannot drag the rest. With a sigma, every camera also contributes (centre − prior) / sigma, its prior being where the model had it on entry, which is how a sensor's poses stay in charge; without one the first camera is held fixed so the model cannot drift as a whole. The frames supply the images whose keypoints the observations index (Reading keypoints); their poses play no part. Log: Adjusted with reprojection_before_px, reprojection_after_px, mean_shift_meters, max_shift_meters, iterations.

reconstruct(images, tracks) -> Reconstruction. From nothing. Every image gets a pinhole prior: the focal length from its EXIF 35 mm equivalent, else 1.2 × its longer side. The seed comes from the ten pairs sharing the most tracks: a candidate counts once its essential-matrix pose has 30 verified inliers; the first whose shared tracks triangulate with a median angle of 3° seeds the model, and if none reaches 3° the widest of them does; no candidate clearing 30 inliers raises ValueError. The seed's first camera sits at the origin and its second a unit baseline away (Seeded with first, second, median_angle_degrees, points). Then, until no image sees twelve placed points: the unregistered image seeing the most is registered by PnP RANSAC — it must hold twelve inliers — its new tracks are triangulated, a local adjustment refines that camera, and whenever the point count has grown 1.5× a global adjustment refines every camera, point and intrinsic and prunes what no longer passes the triangulation checks. The loop is a Registering images count, one turn per image, each logging Registered image and revising the count's registered, points and reprojection_px; an image PnP could not hold logs a Could not register image warning and is absent from the result. One more global adjustment ends the run, and its reprojection is what the result line carries. Log: Reconstructed with registered, unregistered, points, reprojection_px. The scale is arbitrary until aligned, georeferenced or an adjustment with a sigma fixes it.

posed(images, model) -> Array[PosedImage] is the registered images at their solved poses with depth Missing, so it may be shorter than images (Posed images). reposed(frames, model) moves each registered frame to its solved pose and keeps its image and depth; an unregistered frame keeps its prior (Reposed frames).

Placing a free model. A model from reconstruct or cgr.depth.multiview has no scale, no gravity and no place on the Earth:

  • aligned(model, priors: Array[Pose]) — the Umeyama similarity (scale, rotation, translation) carrying the model's camera centres onto the priors', for priors that know altitude and gravity: ARKit poses. Log: Aligned to priors with scale, rotation_degrees, mean_residual_meters.
  • leveled(model) — the dominant plane of the points, by RANSAC, is the ground: the model turns so its normal is +y with the cameras above it and slides so the ground is y = 0. Needs three points and a camera. Log: Leveled with inlier_fraction, tilt_degrees.
  • exif_priors(images, anchor: cg.Location) -> Map[String, Pose] — a prior for every image whose EXIF holds a GPS fix (Reading EXIF counts the images), at its tangent-plane offset from anchor (x north, y up, z east), yawed to its compass heading when it has one, intrinsics from the 35 mm equivalent; an image without a fix has no key. Log: Read EXIF priors with fixes, images, headings.
  • georeferenced(model, priors: Map[String, Pose]) — after levelling, the horizontal similarity (a yaw about y, a scale, a shift in x and z) landing the registered cameras on their fixes; heights scale with the rest but are never tilted. Fewer than two registered cameras with a fix raises ValueError. Log: Georeferenced with fixes, scale, yaw_degrees, horizontal_residual_meters.

anchor is a constant of the site, never the first session's location: a session can be deleted and captured again, and a constant keys each session on itself alone.

Learned depth#

A model's prediction is expensive once and free ever after, which is the case for caching it.

The model. A cgr.depth.Model is a value: a Driver, the capturegraph-free script itself, hashed by its bytes, and Weights, a Hugging Face repository at one commit. Both enter a prediction's cache key, so an edited driver or newer weights predict again and nothing else does. cgr.depth.DA3_LARGE and cgr.depth.PI3X are the built-in values; a model of your own is the same two parts:

mine = cgr.depth.Model(
    driver=cgr.depth.Driver("my_driver.py"),
    weights=cgr.depth.Weights(repo_id="me/my-weights", revision="0123abcd…"),
)

Weights. cgr.depth.snapshot(weights) -> cg.ManagedDir downloads the repository once into the scratch. A cg.ManagedDir is a directory a recipe holds without describing its contents, pinned, evicted and shared like any other value; a driver never touches ~/.cache/huggingface. revision must be a commit hash: a floating "main" would name the snapshot first downloaded forever. predict and multiview fetch the snapshot before taking the GPU lock, so a download never holds the GPU. Log: Downloaded snapshot with repo, revision, bytes.

The driver contract. A driver is a standalone script — torch, numpy and PIL, never capturegraph — run by path in the GPU interpreter:

python my_driver.py --images DIR --weights DIR --output DIR [--multiview]

--images holds NNNNN.jpg files, staged with their longest side at most max_dimension; --weights is the snapshot. For every image the driver writes NNNNN.npy (float32 depth, in the model's units) and NNNNN_conf.npy (float32 confidence in [0, 1]) into --output, both at the staged image's size. With --multiview the images are posed together and the driver also writes cameras.json — a list, one entry per image, of camera_to_world (4×4, OpenCV convention), focal_x, focal_y, center_x, center_y, width, height — beside points.npy (N×3 float32) and colors.npy (N×3 uint8). The two built-in drivers are the reference implementations.

predict(images, model, max_dimension=1600) -> Array[RelativeDepth]. The model's driver runs once over the whole array, one image at a time, under cg.lock("gpu") — a named lock held across every process sharing the scratch, so two GPU stages on one machine never overlap. Loading weights costs seconds and a prediction a fraction of one, so the caller chooses the batch: a session, in the ARKit pipeline below. A RelativeDepth is an OpenEXR of depth in the model's own units (.to_array()) with the model's confidence (.confidence()), metric only up to an affine map in inverse depth — what separates it from a cg.Depth. Log: Predicted depth with model, revision, images, seconds_per_image.

multiview(images, model, max_dimension=1600) -> Multiview. One forward pass over the set. A Multiview is two fields: model, a scale-free Reconstruction (the cameras keyed like every other, the driver's points, no observations), and depths, one RelativeDepth per image in that scale. It is a pose source beside reconstruct, whose points are a seed as they are: aligned carries it onto ARKit poses, leveled and georeferenced place it from EXIF. Log: Predicted multi-view model with model, revision, images, points, seconds.

fitted(prediction, measured: cg.Depth) -> cg.Depth. Monocular models are invariant up to an affine map in inverse depth, so 1/d_metric ≈ a·x + b is solved by iteratively reweighted least squares — the weight is the measured confidence times the model's times a Huber weight on the residual — on the measured map's grid, then applied to the full-resolution prediction: metric depth at the prediction's size, carrying the model's confidence. Fewer than ten usable measured pixels raises ValueError. Log: Fitted to measured depth with scale, shift, inlier_fraction, median_residual_meters.

refined(frames, model) -> Array[PosedImage]. predict over every frame's image, then fitted against each frame's LiDAR: denser, sharper depth in the measurement's metres, which depth_seed and train use with no change of their own. A frame without LiDAR has no metric reference and keeps Missing. Log: Refined depth with model, fitted, without_lidar.

Seeds#

A seed is a cg.PointCloud the gaussians start from. A reconstruction's sparse points, model.points, are already one and are used as they are. Four builders make a seed from other sources; each thins its result to 200 000 points and logs the count:

Seed Points Log
depth_seed(frames) each frame's confident depth pixels (confidence ≥ 0.5, 0.2–40 m), 2 000 per frame, back-projected through its pose (Seeding frames counts them); a frame without depth contributes nothing Seeded from depth
distance_seed(frames, meters) a 48×36 grid of every frame's pixels cast meters along their rays, for captures that measured no depth Seeded at a distance
splat_centers(splats) the gaussian centres of trained splats, so a scene's splat starts from its sessions'; ValueError when every splat is Missing Seeded from splats
merged(clouds: Array[PointCloud]) several seeds as one; ValueError when none is present Merged seeds

Training#

train(frames, seed, iterations=15_000, optimize_cameras=False, depth_weight=0.2) -> Splat runs nerfstudio's splatfacto under cg.lock("gpu"). Each frame's depth map is staged at its native resolution with its confidence, and the trainer adds a depth term — the confidence-weighted LogL1 distance between rendered and measured depth — at depth_weight relative to the photometric loss. depth_weight=0, or frames that measured no depth, is stock splatfacto: panoramas and raw bursts train that way. optimize_cameras refines the poses while training, for poses a sensor estimated rather than a tracker. The run is a Training count with the step, loss … and the gaussian count as the trainer reports them. A Splat is the standard 3DGS PLY; .centers() reads its gaussians back as positions and colours, which is what splat_centers seeds from.

Datasets#

A dataset is an Array[PosedImage]. A PosedImage is an image, the pose that took it with intrinsics at the image's own size, and its depth, a cg.Depth or Missing. Arrays of frames in one world concatenate. Each builder resizes to max_dimension, re-encodes as JPEG and logs a Decoding frames count; a frame whose pose carries no intrinsics is left out.

Three pipelines#

Each is abridged from a target module under the repository's example-server/ — Gates345 and CourtyardPanoramas under 3DGS, Touchdown and CIS under 3D Timelapse — where the same recipes sit beside the procedure, interceptors and pages that From Zero to a Scheduled Target explains.

An ARKit session (Gates345): ARKit poses are the priors, LiDAR the metric reference. Matching is guided by the poses, adjustment holds each camera within 5 cm of ARKit's, and a learned depth is fitted to the LiDAR before training.

@cg.pure_function("session_model/1")
def session_model(capture: cg.SceneCapture) -> cgr.Reconstruction:
    frames = cgr.splats.scene_dataset(capture)
    pairs = cgr.sfm.nearby_pairs(frames.pose)
    model = cgr.sfm.triangulate(frames, cgr.sfm.tracks(frames.image, pairs))
    return cgr.sfm.bundle_adjust(frames, model, position_sigma_meters=0.05)


@cg.pure_function("session_frames/1")
def session_frames(capture: cg.SceneCapture) -> cg.Array[cgr.PosedImage]:
    frames = cgr.splats.scene_dataset(capture)
    return cgr.depth.refined(
        cgr.sfm.reposed(frames, session_model(capture)), cgr.depth.DA3_LARGE
    )


@cg.pure_function("session_splat/1")
def session_splat(capture: cg.SceneCapture) -> cgr.Splat:
    frames = session_frames(capture)
    seed = cgr.splats.merged(
        cg.Array[cg.PointCloud]([cgr.splats.depth_seed(frames), session_model(capture).points])
    )
    return cgr.splats.train(frames, seed)

A whole-scene splat concatenates the sessions' session_frames — each a cache hit — and seeds from every session's points and splat centres.

Panoramas across sweeps (CourtyardPanoramas): GPS and compass are the priors, at metres of accuracy, and no sweep has depth. The sessions are a cg.Map keyed by capture date; .values() is its entries as an Array, and .map applies a function to each. PanoramaSession is the study's own session Struct, of which the recipe reads two fields:

SITE_ANCHOR = cg.Location(latitude=42.44441, longitude=-76.48039)


class PanoramaSession(cg.Struct):
    panorama: cg.ImagePanorama
    location: cg.Location


def courtyard_frames(sessions: cg.Map[cg.Date, PanoramaSession]) -> cg.Array[cgr.PosedImage]:
    sweeps = sessions.values().map(
        lambda s: cgr.splats.panorama_dataset(s.panorama, s.location, SITE_ANCHOR)
    )
    return cg.Array[cgr.PosedImage]([f for sweep in sweeps if not cg.is_missing(sweep) for f in sweep])


@cg.pure_function("courtyard_model/1")
def courtyard_model(sessions: cg.Map[cg.Date, PanoramaSession]) -> cgr.Reconstruction:
    frames = courtyard_frames(sessions)
    pairs = cgr.sfm.nearby_pairs(frames.pose, neighbors=64, max_distance_meters=30.0)
    model = cgr.sfm.triangulate(frames, cgr.sfm.tracks(frames.image, pairs))
    return cgr.sfm.bundle_adjust(frames, model, position_sigma_meters=3.0)


@cg.pure_function("courtyard_splat/1")
def courtyard_splat(sessions: cg.Map[cg.Date, PanoramaSession]) -> cgr.Splat:
    model = courtyard_model(sessions)
    frames = cgr.sfm.reposed(courtyard_frames(sessions), model)
    return cgr.splats.train(frames, model.points, iterations=30_000, depth_weight=0)

A session whose panorama is not yet captured maps to Missing and is skipped. A frame's own sweep sits at distance zero, so neighbors must be wide enough to reach past it to the other sweeps.

A raw burst with EXIF fixes (the Touchdown and CIS timelapses): no poses, no depth, a GPS fix on some photographs. The model is built from nothing, given gravity, and landed on its fixes so every session's splat shares one georeferenced frame.

@cg.pure_function("burst_splat/1")
def burst_splat(images: cg.Array[cg.Image]) -> cgr.Splat:
    tracks = cgr.sfm.tracks(images, cgr.sfm.exhaustive_pairs(len(images)))
    model = cgr.sfm.leveled(cgr.sfm.reconstruct(images, tracks))
    model = cgr.sfm.georeferenced(model, cgr.sfm.exif_priors(images, SITE_ANCHOR))
    frames = cgr.sfm.posed(images, model)
    return cgr.splats.train(frames, model.points, depth_weight=0)

A burst is small, so every pair is matched. georeferenced needs two registered cameras with a fix; the full target checks that first and keeps a burst without them in the levelled model's own frame. On a GPU box, cgr.depth.multiview(images, cgr.depth.PI3X).model replaces reconstruct and gives poses and points in seconds; leveled and georeferenced apply unchanged.

The machine#

CPU stages — keypoints, match, tracks — release the interpreter lock and run through the process's thread pool, sized to the CPU count, so they overlap another target's GPU work. GPU stages — predict, multiview, train — serialise on cg.lock("gpu"), a waiting call saying who holds the lock and for how long. They run in a separate interpreter named by the CG_GPU_PYTHON environment variable — cgr.GPU_PYTHON_ENV is that variable's name — else the one the ns-train on the path belongs to; the package's own environment never imports torch. That interpreter needs nerfstudio (torch, gsplat) for train, depth-anything-3 for cgr.depth.DA3_LARGE and Pi3's pi3 package for cgr.depth.PI3X; a model of your own needs whatever its driver imports.