Skip to main content

Two-view reconstruction and splat training

@luma.gl/graph/gpu-sfm estimates a sparse scene from two overlapping, equally sized, undistorted grayscale images with known pinhole intrinsics. WebGPU extracts one Shi–Tomasi corner per 10-pixel cell, computes binary patch descriptors, and matches them in both directions. A CPU solver estimates an essential matrix with eight-point RANSAC, refines the relative pose, and triangulates positive-depth points with measurable parallax.

import {reconstructImagePair} from '@luma.gl/graph/gpu-sfm';
import {trainSplatScene} from '@luma.gl/engine/splats/training';

const reconstruction = await reconstructImagePair(device, width, height, [
{imageId: 'left', intrinsics: leftIntrinsics, gray: leftGray},
{imageId: 'right', intrinsics: rightIntrinsics, gray: rightGray}
]);
const {splats, initialMeanSquaredError, finalMeanSquaredError} = await trainSplatScene(
device, reconstruction,
[
{imageId: 'left', width, height, rgba: leftLinearRGBA},
{imageId: 'right', width, height, rgba: rightLinearRGBA}
],
{iterations: 100, maxSplats: 48}
);

The interchange type is SparseReconstruction. Each camera has an image ID, pixel intrinsics [fx, fy, cx, cy] and three row-major world-to-camera affine rows. Each point has a world position and observations with image IDs and pixel coordinates. Photographs travel separately. Externally reconstructed scenes can retain their original world coordinates.

Two-view SfM puts the first camera at the origin and assigns unit length to the baseline. To recover physical units, multiply the points and camera translations by the measured camera separation. Intrinsics and pixel coordinates must be scaled when resizing photographs. Inputs use pixel centers at half integers and camera axes pointing right, down, and forward.

The trainer initializes scale and color from observed training pixels and fits position, linear scales, rotation, opacity and RGB using GPU mean-squared-error gradients and Adam. Each iteration uses one training image. Supply trainingImageIds to reserve additional calibrated views for evaluation. A reserved view needs its own known pose in the reconstruction frame. The returned splats is a renderer-ready SplatSource.

Load a COLMAP capture​

The optional @luma.gl/engine/splats/training/colmap adapter uses loaders.gl 5.0.4 or later. Use IDs from source.model.images to select registered views. It supports undistorted PINHOLE and SIMPLE_PINHOLE models. Supply full-frame photographs corresponding to the calibration, including proportionally resized copies. Cropped or reoriented images require updated calibration. The adapter resizes the images and observations to the training resolution and converts sRGB pixels to linear RGB in a browser or worker with OffscreenCanvas.

import {load} from '@loaders.gl/core';
import {COLMAPSource} from '@loaders.gl/scene/colmap/source';
import {loadCOLMAPTrainingInputs} from '@luma.gl/engine/splats/training/colmap';
import {trainSplatScene} from '@luma.gl/engine/splats/training';

const source = await COLMAPSource.open(camerasUrl, {imageBaseUrl}, {load});
const {reconstruction, photos} = await loadCOLMAPTrainingInputs(source, {
imageIds: registeredImageIds, width: 96, height: 64
});
const result = await trainSplatScene(device, reconstruction, photos, {iterations: 100});

Camera and photo IDs are decimal strings of the original numeric COLMAP IDs. Use the same strings for trainingImageIds to reserve evaluation views. Landmark positions and camera translations retain the capture's world coordinates.

Prototype limits​

Feature descriptors compare fixed-size upright patches. The two-view solver requires overlap, distinct camera centers, and well-distributed matches. Incremental registration, bundle adjustment, unknown intrinsics, distortion estimation and physical scale recovery are future work. The fixed-count trainer bins projected four-sigma bounds into tiles, sorts by current camera depth each step, and uses black background and view-independent color. Start with small images and tens of points. The GPU counts projected overlaps, scans tile counts into offsets, and scatters splats in depth order. Each view reads a single count before submission. Pair scratch grows to the largest visible list seen and is reused for smaller lists. The result reports peakTileEntries and peakPairScratchBytes (indices, forward transmittance and per-pixel gradient contributions). Oversized gradient scratch buffers are rejected.

Real-image check​

Using Mip-NeRF 360 Bonsai photographs DSCF5565 and DSCF5567 at 640 × 426, the GPU matcher found 260 mutual matches. The solver retained 219 points. Against the original calibration the relative rotation differed by 0.113° and the translation direction by 0.218°. Only intrinsics and image pixels entered pose recovery.

For the training check, the two recovered views were reduced to 48 × 32 in linear RGB. A 48-splat scene trained for 100 alternating updates at learning rate 0.035. DSCF5566 was reserved for evaluation using its COLMAP pose aligned to the first camera and the recovered unit baseline. Its RGB MSE decreased from 0.036995 to 0.002858. These results measure a small two-view reconstruction at thumbnail resolution. Bonsai source images and calibration

Reproducible optimization and held-out evaluation​

Specify seed to shuffle the selected training image IDs once per epoch. Without a seed, training retains its cyclic order. learningRates overrides the scalar learning rate for position, scale, rotation, opacity and color. Zero freezes that group. Linear-RGB PSNR assumes unit peak radiance and is reported for each held-out view in heldOutPSNR. Identical inputs and seed give repeatable order; floating-point results may vary by device.

peakBufferBytes counts owned training buffers and physical transient graph buffers. It excludes driver allocations and CPU staging memory. To accumulate GPU milliseconds per graph stage over optimizer updates, enable profile on a device with timestamp queries. Timestamp readback synchronizes the device. The optional capture benchmark reports this time separately from end-to-end elapsed time.

VITE_SPLAT_CAPTURE='{"camerasUrl":"http://localhost:8000/sparse/0/cameras.bin","imageBaseUrl":"http://localhost:8000/images","imageIds":[1,2,3],"trainingImageIds":[1,3],"width":48,"height":32,"iterations":100,"maxSplats":48,"seed":73}' LUMA_TEST_BROWSER_BENCHMARKS=true yarn test-headless --reporter=verbose modules/engine/test/splats/training/capture-benchmark.spec.ts

Bounded densification and pruning​

Set adaptation: {initialSplats, interval, pruneOpacity, splitGradient} and an explicit maxSplats to change the training population. At each interval the trainer compacts survivors, preserves their Adam moments, and splits the highest-gradient candidates along their largest rotated scale axis. Both children inherit their parent's optimizer history and share its opacity. One seed survives even if all fall below the pruning threshold. Decisions use optimizer history from training images. The result includes split and prune counts, and its exported arrays contain only active splats.

The GPU allocates parameter and optimizer buffers up to the population cap. The tile planner excludes inactive slots from visible-pair storage. Each topology decision reads parameters and moments back to the CPU, so larger intervals reduce synchronization frequency.

View-dependent appearance​

Pass sphericalHarmonicsDegree: 1 to fit the first non-DC band along with the base linear RGB. Training evaluates the normalized world-space camera-to-splat direction and differentiates both its direction and the nine coefficients. The color-group learning rate applies to both. The resulting SplatSource carries sphericalHarmonicsDegree: 1 and three basis-major RGB triplets per active Gaussian. Pass it directly to makeGPUSplatData. Splitting and pruning move each row's coefficient and optimizer state together.

Degree zero uses constant RGB. Higher bands remain available to the renderer for externally produced sources.