Skip to content

mlx3d.capture

mlx3d.capture

One-command capture pipeline: photos or video -> poses -> 3DGS -> PLY.

CaptureConfig dataclass

Source code in src/mlx3d/capture/pipeline.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@dataclass
class CaptureConfig:
    quality: str = "balanced"
    """Preset for iterations / resolution / frame count: fast, balanced, best."""
    poses: str = "auto"
    """Pose source: ``auto`` (COLMAP if installed, else built-in SfM),
    ``colmap``, ``builtin``, or ``existing`` (reuse ``<out>/sparse/0``)."""
    refine_poses: str = "auto"
    """Joint pose refinement during training: ``auto`` (on for built-in SfM
    poses), ``on``, or ``off``."""
    iters: int | None = None
    num_frames: int | None = None
    train_max_dim: int | None = None
    sh_degree: int | None = None
    method: str = "vanilla"
    """Trainer strategy: vanilla, mcmc, or 2dgs."""
    viewer: bool = True
    viewer_port: int = 8090
    viewer_open_browser: bool = True
    keep_open: bool = False
    """Keep the live viewer alive after training finishes."""
    low_memory: bool = False
    image_cache: str = "uint8"
    save_every: int = 1000
    compact_min_opacity: float = 0.005
    seed: int = 0
    overwrite: bool = False
    """Re-run all stages even when outputs already exist."""

    def resolved(self) -> "CaptureConfig":
        if self.quality not in QUALITY_PRESETS:
            raise ValueError(f"quality must be one of {sorted(QUALITY_PRESETS)}")
        preset = QUALITY_PRESETS[self.quality]
        cfg = CaptureConfig(**asdict(self))
        cfg.iters = self.iters or preset.iters
        cfg.num_frames = self.num_frames or preset.num_frames
        cfg.train_max_dim = self.train_max_dim or preset.train_max_dim
        cfg.sh_degree = preset.sh_degree if self.sh_degree is None else self.sh_degree
        return cfg

quality = 'balanced' class-attribute instance-attribute

Preset for iterations / resolution / frame count: fast, balanced, best.

poses = 'auto' class-attribute instance-attribute

Pose source: auto (COLMAP if installed, else built-in SfM), colmap, builtin, or existing (reuse <out>/sparse/0).

refine_poses = 'auto' class-attribute instance-attribute

Joint pose refinement during training: auto (on for built-in SfM poses), on, or off.

method = 'vanilla' class-attribute instance-attribute

Trainer strategy: vanilla, mcmc, or 2dgs.

keep_open = False class-attribute instance-attribute

Keep the live viewer alive after training finishes.

overwrite = False class-attribute instance-attribute

Re-run all stages even when outputs already exist.

SfmConfig dataclass

Source code in src/mlx3d/capture/sfm.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@dataclass
class SfmConfig:
    max_dim: int = 1024
    """Images are downscaled to this size for feature extraction/matching."""
    n_features: int = 4096
    match_ratio: float = 0.75
    min_pair_inliers: int = 30
    sequential_window: int = 8
    exhaustive_threshold: int = 60
    """Match all pairs when there are at most this many images."""
    ransac_px: float = 2.0
    pnp_px: float = 6.0
    min_pnp_inliers: int = 12
    min_tri_angle_deg: float = 1.0
    init_min_tri_angle_deg: float = 3.0
    max_reproj_px: float = 4.0
    ba_every: int = 8
    """Run global bundle adjustment after this many new registrations."""
    refine_focal: bool = True
    seed: int = 0

max_dim = 1024 class-attribute instance-attribute

Images are downscaled to this size for feature extraction/matching.

exhaustive_threshold = 60 class-attribute instance-attribute

Match all pairs when there are at most this many images.

ba_every = 8 class-attribute instance-attribute

Run global bundle adjustment after this many new registrations.

has_colmap()

Whether the colmap binary is available on PATH.

Source code in src/mlx3d/capture/colmap_wrap.py
16
17
18
def has_colmap() -> bool:
    """Whether the ``colmap`` binary is available on PATH."""
    return shutil.which("colmap") is not None

run_colmap(images_dir, workspace, sequential=False, camera_model='OPENCV', single_camera=True, log=print)

Run COLMAP SfM on images_dir and return the sparse model directory.

Parameters:

Name Type Description Default
images_dir str

directory of input images.

required
workspace str

output directory; receives database.db, sparse/ and colmap.log.

required
sequential bool

use the sequential matcher (video / ordered captures) instead of exhaustive matching.

False
camera_model str

COLMAP camera model for feature extraction.

'OPENCV'
single_camera bool

share one camera across all images (same device).

True
Source code in src/mlx3d/capture/colmap_wrap.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def run_colmap(
    images_dir: str,
    workspace: str,
    sequential: bool = False,
    camera_model: str = "OPENCV",
    single_camera: bool = True,
    log=print,
) -> str:
    """Run COLMAP SfM on ``images_dir`` and return the sparse model directory.

    Args:
        images_dir: directory of input images.
        workspace: output directory; receives ``database.db``, ``sparse/`` and
            ``colmap.log``.
        sequential: use the sequential matcher (video / ordered captures)
            instead of exhaustive matching.
        camera_model: COLMAP camera model for feature extraction.
        single_camera: share one camera across all images (same device).
    """
    colmap = shutil.which("colmap")
    if colmap is None:
        raise RuntimeError("COLMAP binary not found on PATH.")
    os.makedirs(workspace, exist_ok=True)
    db = os.path.join(workspace, "database.db")
    sparse = os.path.join(workspace, "sparse")
    log_path = os.path.join(workspace, "colmap.log")
    os.makedirs(sparse, exist_ok=True)

    _run(
        [
            colmap,
            "feature_extractor",
            "--database_path",
            db,
            "--image_path",
            images_dir,
            "--ImageReader.camera_model",
            camera_model,
            "--ImageReader.single_camera",
            "1" if single_camera else "0",
        ],
        log_path,
        log,
    )
    if sequential:
        matcher = [
            colmap,
            "sequential_matcher",
            "--database_path",
            db,
            "--SequentialMatching.overlap",
            "15",
        ]
    else:
        matcher = [colmap, "exhaustive_matcher", "--database_path", db]
    _run(matcher, log_path, log)
    _run(
        [
            colmap,
            "mapper",
            "--database_path",
            db,
            "--image_path",
            images_dir,
            "--output_path",
            sparse,
        ],
        log_path,
        log,
    )

    models = [
        os.path.join(sparse, d)
        for d in sorted(os.listdir(sparse))
        if os.path.isdir(os.path.join(sparse, d))
    ]
    if not models:
        raise RuntimeError(
            "COLMAP produced no reconstruction. The capture likely lacks "
            "overlap or texture; try more/sharper images with generous overlap."
        )
    best = max(models, key=_model_image_count)
    target = os.path.join(sparse, "0")
    if best != target:
        # Promote the largest model to sparse/0 (swap directories).
        tmp = os.path.join(sparse, "_tmp_swap")
        if os.path.exists(target):
            os.rename(target, tmp)
        os.rename(best, target)
        if os.path.exists(tmp):
            os.rename(tmp, best)
    n = _model_image_count(target)
    log(f"  COLMAP registered {n} images (model {os.path.basename(best)}).")
    return target

estimate_focal_px(image_path, prior=1.2)

Estimate the focal length in pixels for an image.

Uses the EXIF 35mm-equivalent focal length when present (mapping the 36mm film width onto the image's long side), otherwise falls back to prior * max(width, height) — the same default prior COLMAP uses.

Returns (focal_px, source) with source in {"exif", "prior"}.

Source code in src/mlx3d/capture/frames.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def estimate_focal_px(image_path: str, prior: float = 1.2) -> tuple[float, str]:
    """Estimate the focal length in pixels for an image.

    Uses the EXIF 35mm-equivalent focal length when present (mapping the 36mm
    film width onto the image's long side), otherwise falls back to
    ``prior * max(width, height)`` — the same default prior COLMAP uses.

    Returns ``(focal_px, source)`` with ``source`` in ``{"exif", "prior"}``.
    """
    from PIL import ExifTags, Image

    with Image.open(image_path) as img:
        w, h = img.size
        try:
            exif = img.getexif()
            f35 = exif.get_ifd(ExifTags.IFD.Exif).get(ExifTags.Base.FocalLengthIn35mmFilm)
        except Exception:
            f35 = None
    if f35:
        return float(f35) / 36.0 * max(w, h), "exif"
    return prior * max(w, h), "prior"

extract_video_frames(video, out_dir, num_frames=150, overscan=2.5, jpeg_quality=2, log=print)

Extract num_frames sharp frames from video into out_dir.

ffmpeg samples the video evenly at overscan * num_frames frames, then :func:select_sharpest keeps the sharpest frame per time bucket and the rejects are deleted. Returns the kept frame paths (sorted, temporal order).

Source code in src/mlx3d/capture/frames.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def extract_video_frames(
    video: str,
    out_dir: str,
    num_frames: int = 150,
    overscan: float = 2.5,
    jpeg_quality: int = 2,
    log=print,
) -> list[str]:
    """Extract ``num_frames`` sharp frames from ``video`` into ``out_dir``.

    ffmpeg samples the video evenly at ``overscan * num_frames`` frames, then
    :func:`select_sharpest` keeps the sharpest frame per time bucket and the
    rejects are deleted. Returns the kept frame paths (sorted, temporal order).
    """
    ffmpeg = _ffmpeg_or_raise()
    os.makedirs(out_dir, exist_ok=True)
    raw = int(math.ceil(num_frames * max(overscan, 1.0)))
    duration = _video_duration_seconds(video)
    if duration and duration > 0:
        fps = raw / duration
        vf = f"fps={fps:.6f}"
        log(f"Sampling {video} at {fps:.2f} fps (~{raw} frames from {duration:.1f}s)...")
    else:
        # Unknown duration (no ffprobe): sample at a fixed rate.
        vf = "fps=4"
        log(f"Sampling {video} at 4 fps (unknown duration)...")
    pattern = os.path.join(out_dir, "frame_%05d.jpg")
    subprocess.run(
        [
            ffmpeg,
            "-y",
            "-loglevel",
            "error",
            "-i",
            video,
            "-vf",
            vf,
            "-q:v",
            str(jpeg_quality),
            pattern,
        ],
        check=True,
    )
    extracted = list_images(out_dir)
    if not extracted:
        raise RuntimeError(f"ffmpeg extracted no frames from {video!r}.")
    keep = set(select_sharpest(extracted, num_frames))
    for p in extracted:
        if p not in keep:
            os.remove(p)
    kept = list_images(out_dir)
    log(f"Kept {len(kept)} sharp frames of {len(extracted)} sampled.")
    return kept

is_video(path)

Whether path looks like a video file the pipeline can ingest.

Source code in src/mlx3d/capture/frames.py
32
33
34
def is_video(path: str) -> bool:
    """Whether ``path`` looks like a video file the pipeline can ingest."""
    return os.path.splitext(path)[1].lower() in VIDEO_EXTENSIONS

list_images(directory)

Sorted image files (by name) directly inside directory.

Source code in src/mlx3d/capture/frames.py
37
38
39
40
41
42
43
44
def list_images(directory: str) -> list[str]:
    """Sorted image files (by name) directly inside ``directory``."""
    names = [
        n
        for n in sorted(os.listdir(directory))
        if os.path.splitext(n)[1].lower() in IMAGE_EXTENSIONS
    ]
    return [os.path.join(directory, n) for n in names]

select_sharpest(paths, target)

Pick target frames from a temporally ordered list of frame paths.

The sequence is split into target contiguous buckets and the sharpest frame of each bucket is kept, preserving even temporal coverage while dropping blurred frames.

Source code in src/mlx3d/capture/frames.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def select_sharpest(paths: list[str], target: int) -> list[str]:
    """Pick ``target`` frames from a temporally ordered list of frame paths.

    The sequence is split into ``target`` contiguous buckets and the sharpest
    frame of each bucket is kept, preserving even temporal coverage while
    dropping blurred frames.
    """
    if target <= 0:
        raise ValueError("target must be positive.")
    if len(paths) <= target:
        return list(paths)
    scores = [sharpness_score(_load_gray(p)) for p in paths]
    keep: list[str] = []
    for b in range(target):
        lo = round(b * len(paths) / target)
        hi = round((b + 1) * len(paths) / target)
        best = max(range(lo, hi), key=lambda i: scores[i])
        keep.append(paths[best])
    return keep

sharpness_score(gray)

Variance of the Laplacian; higher means sharper. gray is (H, W) float.

Source code in src/mlx3d/capture/frames.py
58
59
60
61
62
63
def sharpness_score(gray: np.ndarray) -> float:
    """Variance of the Laplacian; higher means sharper. ``gray`` is (H, W) float."""
    lap = (
        gray[:-2, 1:-1] + gray[2:, 1:-1] + gray[1:-1, :-2] + gray[1:-1, 2:] - 4.0 * gray[1:-1, 1:-1]
    )
    return float(lap.var())

run_capture(input_path, out, config=None, log=print)

Run the full photos/video -> splat pipeline. Returns a summary dict.

Source code in src/mlx3d/capture/pipeline.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
def run_capture(input_path: str, out: str, config: CaptureConfig | None = None, log=print):
    """Run the full photos/video -> splat pipeline. Returns a summary dict."""
    cfg = (config or CaptureConfig()).resolved()
    out = os.path.abspath(os.path.expanduser(out))
    os.makedirs(out, exist_ok=True)
    summary: dict[str, object] = {"input": os.path.abspath(input_path), "out": out}
    stages: list[_Stage] = []
    t_all = time.perf_counter()

    _banner(log, "1/4 Frames")
    t0 = time.perf_counter()
    images_dir, frames_info = _stage_frames(input_path, out, cfg, log)
    stages.append(_Stage("frames", time.perf_counter() - t0, frames_info))

    _banner(log, "2/4 Camera poses")
    t0 = time.perf_counter()
    pose_info = _stage_poses(images_dir, out, cfg, str(frames_info.get("source")), log)
    stages.append(_Stage("poses", time.perf_counter() - t0, pose_info))

    _banner(log, "3/4 Train 3D Gaussian Splatting")
    t0 = time.perf_counter()
    train_info = _stage_train(out, images_dir, cfg, pose_info, log)
    stages.append(_Stage("train", time.perf_counter() - t0, train_info))

    _banner(log, "4/4 Export")
    t0 = time.perf_counter()
    export_info = _stage_export(out, cfg, log)
    stages.append(_Stage("export", time.perf_counter() - t0, export_info))

    summary["stages"] = {s.name: {"seconds": round(s.seconds, 2), **s.info} for s in stages}
    summary["total_seconds"] = round(time.perf_counter() - t_all, 2)
    summary["splat"] = os.path.join(out, "splat.ply")
    with open(os.path.join(out, "capture.json"), "w") as f:
        json.dump(summary, f, indent=2)

    total_min = summary["total_seconds"] / 60.0
    _banner(log, "Done")
    log(f"Splat: {summary['splat']}  ({total_min:.1f} min total)")
    log(f"View it anytime:  mlx3d-view {summary['splat']}")

    if cfg.viewer and cfg.keep_open:
        log("Live viewer stays open. Press Ctrl-C to exit.")
        try:
            while True:
                time.sleep(1.0)
        except KeyboardInterrupt:
            pass
    return summary

run_sfm(image_paths, out_root, config=None, log=print)

Estimate camera poses + sparse points for image_paths.

Writes a COLMAP binary sparse model under out_root/sparse/0 (only registered images are included) and returns an :class:SfmResult.

Source code in src/mlx3d/capture/sfm.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
def run_sfm(
    image_paths: list[str],
    out_root: str,
    config: SfmConfig | None = None,
    log=print,
) -> SfmResult:
    """Estimate camera poses + sparse points for ``image_paths``.

    Writes a COLMAP binary sparse model under ``out_root/sparse/0`` (only
    registered images are included) and returns an :class:`SfmResult`.
    """
    cv2 = _import_cv2()
    from ..datasets import save_colmap

    cfg = config or SfmConfig()
    if len(image_paths) < 3:
        raise ValueError("SfM needs at least 3 images.")
    cv2.setRNGSeed(cfg.seed)

    # ---- load (downscaled) images, shared intrinsics prior
    from PIL import Image

    with Image.open(image_paths[0]) as im0:
        orig_w, orig_h = im0.size
    scale = min(1.0, cfg.max_dim / max(orig_w, orig_h))
    w, h = round(orig_w * scale), round(orig_h * scale)
    focal_prior, focal_source = estimate_focal_px(image_paths[0])
    f = focal_prior * scale
    K = np.array([[f, 0, w / 2.0], [0, f, h / 2.0], [0, 0, 1.0]])
    log(
        f"  {len(image_paths)} images at {w}x{h} (SfM scale {scale:.3f}), "
        f"focal prior {focal_prior:.0f} px ({focal_source})"
    )

    sift = cv2.SIFT_create(nfeatures=cfg.n_features)
    keypoints, descriptors, colors = [], [], []
    for p in image_paths:
        with Image.open(p) as img:
            if img.size != (orig_w, orig_h):
                raise ValueError(
                    "The built-in SfM assumes one camera: all images must share "
                    f"one size, but {os.path.basename(p)} is {img.size} vs "
                    f"{(orig_w, orig_h)}. Use COLMAP for mixed captures."
                )
            rgb = np.asarray(img.convert("RGB").resize((w, h), Image.BILINEAR))
        gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
        kps, desc = sift.detectAndCompute(gray, None)
        if desc is None or len(kps) < 10:
            kps, desc = [], np.zeros((0, 128), dtype=np.float32)
        pts = np.array([kp.pt for kp in kps], dtype=np.float64).reshape(-1, 2)
        px = np.clip(pts.round().astype(int), 0, [w - 1, h - 1])
        keypoints.append(pts)
        descriptors.append(desc)
        colors.append(rgb[px[:, 1], px[:, 0]].astype(np.float64) / 255.0)
    log(f"  SIFT: median {int(np.median([len(k) for k in keypoints]))} features/image")

    # ---- pairwise matching + geometric verification
    pairs = _candidate_pairs(len(image_paths), cfg)
    matcher = cv2.BFMatcher(cv2.NORM_L2)
    matches: dict[tuple[int, int], np.ndarray] = {}
    for i, j in pairs:
        if min(len(keypoints[i]), len(keypoints[j])) < cfg.min_pair_inliers:
            continue
        m = _match_pair(matcher, descriptors[i], descriptors[j], cfg.match_ratio)
        if len(m) < cfg.min_pair_inliers:
            continue
        p1, p2 = keypoints[i][m[:, 0]], keypoints[j][m[:, 1]]
        E, inl = cv2.findEssentialMat(
            p1, p2, K, method=cv2.RANSAC, prob=0.999, threshold=cfg.ransac_px
        )
        if E is None or inl is None:
            continue
        m = m[inl.ravel().astype(bool)]
        if len(m) >= cfg.min_pair_inliers:
            matches[(i, j)] = m
    log(f"  Verified {len(matches)} image pairs (of {len(pairs)} candidates)")
    if not matches:
        raise RuntimeError(
            "No image pairs with enough matches. The images likely do not overlap or lack texture."
        )

    rec = _Reconstruction(keypoints, colors, K, cfg)

    # ---- initialization: best verified pair with a healthy triangulation angle
    def _init_pair_stats(i, j, m):
        p1, p2 = keypoints[i][m[:, 0]], keypoints[j][m[:, 1]]
        E, inl = cv2.findEssentialMat(
            p1, p2, K, method=cv2.RANSAC, prob=0.999, threshold=cfg.ransac_px
        )
        if E is None:
            return None
        ok = inl.ravel().astype(bool)
        n_pose, R, t, mask = cv2.recoverPose(E, p1[ok], p2[ok], K)
        if n_pose < cfg.min_pair_inliers:
            return None
        good = mask.ravel().astype(bool)
        P1 = K @ np.hstack([np.eye(3), np.zeros((3, 1))])
        P2 = K @ np.hstack([R, t])
        X = cv2.triangulatePoints(P1, P2, p1[ok][good].T, p2[ok][good].T)
        X = (X[:3] / np.maximum(np.abs(X[3]), 1e-12) * np.sign(X[3])).T
        angles = _triangulation_angles(X, np.zeros(3), (-R.T @ t).ravel())
        return R, t.ravel(), m[ok][good], X, float(np.median(angles)), int(n_pose)

    best = None
    for (i, j), m in sorted(matches.items(), key=lambda kv: -len(kv[1]))[:40]:
        stats = _init_pair_stats(i, j, m)
        if stats is None:
            continue
        R, t, m_good, X, med_angle, n_pose = stats
        score = n_pose * min(1.0, med_angle / cfg.init_min_tri_angle_deg) ** 2
        if best is None or score > best[0]:
            best = (score, i, j, R, t, m_good, X, med_angle)
    if best is None:
        raise RuntimeError("Could not find a valid initial image pair.")
    _, i0, j0, R1, t1, m_good, X, med_angle = best
    log(
        f"  Init pair ({os.path.basename(image_paths[i0])}, "
        f"{os.path.basename(image_paths[j0])}): {len(m_good)} points, "
        f"median angle {med_angle:.1f} deg"
    )
    rec.poses[i0] = (np.eye(3), np.zeros(3))
    rec.poses[j0] = (R1, t1)
    keep = X[:, 2] > 0
    for xyz, (f1, f2) in zip(X[keep], m_good[keep]):
        rec.add_point(xyz, {i0: int(f1), j0: int(f2)})

    # ---- incremental registration
    def correspondences_2d3d(img: int):
        obj, pix, feats = [], [], []
        for (a, b), m in matches.items():
            if a == img and b in rec.poses:
                new_f, reg_i, reg_f = m[:, 0], b, m[:, 1]
            elif b == img and a in rec.poses:
                new_f, reg_i, reg_f = m[:, 1], a, m[:, 0]
            else:
                continue
            for nf, rf in zip(new_f, reg_f):
                pid = rec.feat_to_point[reg_i].get(int(rf))
                if pid is not None and rec.point_obs[pid]:
                    obj.append(rec.points[pid])
                    pix.append(keypoints[img][nf])
                    feats.append((int(nf), pid))
        return np.array(obj), np.array(pix), feats

    def triangulate_new(img: int) -> int:
        added = 0
        R_new, t_new = rec.poses[img]
        P_new = K @ np.hstack([R_new, t_new[:, None]])
        c_new = rec.center(img)
        for (a, b), m in matches.items():
            if a == img and b in rec.poses:
                other, f_img, f_oth = b, m[:, 0], m[:, 1]
            elif b == img and a in rec.poses:
                other, f_img, f_oth = a, m[:, 1], m[:, 0]
            else:
                continue
            R_o, t_o = rec.poses[other]
            P_o = K @ np.hstack([R_o, t_o[:, None]])
            c_o = rec.center(other)
            for fi, fo in zip(f_img, f_oth):
                fi, fo = int(fi), int(fo)
                pid_i = rec.feat_to_point[img].get(fi)
                pid_o = rec.feat_to_point[other].get(fo)
                if pid_i is not None and pid_o is None:
                    rec.add_observation(pid_i, other, fo)
                    continue
                if pid_o is not None and pid_i is None:
                    rec.add_observation(pid_o, img, fi)
                    continue
                if pid_i is not None or pid_o is not None:
                    continue
                X4 = cv2.triangulatePoints(
                    P_new, P_o, keypoints[img][fi][:, None], keypoints[other][fo][:, None]
                )
                if abs(X4[3, 0]) < 1e-12:
                    continue
                xyz = (X4[:3, 0] / X4[3, 0]).ravel()
                z1 = (R_new @ xyz + t_new)[2]
                z2 = (R_o @ xyz + t_o)[2]
                if z1 <= 0 or z2 <= 0:
                    continue
                uv1 = _project((R_new @ xyz + t_new)[None], K[0, 0], K[0, 2], K[1, 2])[0]
                uv2 = _project((R_o @ xyz + t_o)[None], K[0, 0], K[0, 2], K[1, 2])[0]
                if (
                    np.linalg.norm(uv1 - keypoints[img][fi]) > cfg.max_reproj_px
                    or np.linalg.norm(uv2 - keypoints[other][fo]) > cfg.max_reproj_px
                ):
                    continue
                angle = _triangulation_angles(xyz[None], c_new, c_o)[0]
                if angle < cfg.min_tri_angle_deg:
                    continue
                rec.add_point(xyz, {img: fi, other: fo})
                added += 1
        return added

    triangulate_new(i0)  # extend the initial pair's tracks to shared neighbors
    failed: set[int] = set()
    since_ba = 0
    while True:
        remaining = [i for i in range(len(image_paths)) if i not in rec.poses and i not in failed]
        if not remaining:
            break
        scored = []
        for img in remaining:
            obj, pix, feats = correspondences_2d3d(img)
            if len(obj) >= cfg.min_pnp_inliers:
                scored.append((len(obj), img, obj, pix, feats))
        if not scored:
            break
        _, img, obj, pix, feats = max(scored, key=lambda s: s[0])
        ok, rvec, tvec, inl = cv2.solvePnPRansac(
            obj.reshape(-1, 1, 3),
            pix.reshape(-1, 1, 2),
            K,
            None,
            reprojectionError=cfg.pnp_px,
            confidence=0.999,
            iterationsCount=500,
            flags=cv2.SOLVEPNP_EPNP,
        )
        if not ok or inl is None or len(inl) < cfg.min_pnp_inliers:
            failed.add(img)
            continue
        inl = inl.ravel()
        rvec, tvec = cv2.solvePnPRefineLM(
            obj[inl].reshape(-1, 1, 3), pix[inl].reshape(-1, 1, 2), K, None, rvec, tvec
        )
        R = cv2.Rodrigues(rvec)[0]
        rec.poses[img] = (R, tvec.ravel())
        for k in inl:
            feat, pid = feats[k]
            rec.add_observation(pid, img, feat)
        n_new = triangulate_new(img)
        log(
            f"  Registered {os.path.basename(image_paths[img])}: "
            f"{len(inl)} PnP inliers, +{n_new} points "
            f"({len(rec.poses)}/{len(image_paths)} images)"
        )
        since_ba += 1
        if since_ba >= cfg.ba_every:
            rec.bundle_adjust(max_nfev=20, log=log)
            rec.filter_points()
            since_ba = 0

    log("  Final bundle adjustment...")
    rec.bundle_adjust(max_nfev=75, log=log)
    removed = rec.filter_points()
    if removed:
        log(f"  Filtered {removed} unstable points")

    registered = sorted(rec.poses)
    if len(registered) < 3:
        raise RuntimeError(
            f"Only {len(registered)} of {len(image_paths)} images registered; "
            "not enough for training. Try COLMAP, more overlap, or sharper images."
        )
    skipped = len(image_paths) - len(registered)
    if skipped:
        log(f"  Warning: {skipped} images could not be registered and were skipped.")

    # ---- export at the original resolution
    import mlx.core as mx

    inv_scale = 1.0 / scale
    f_full = rec.K[0, 0] * inv_scale
    cams, names = [], []
    for img in registered:
        R, t = rec.poses[img]
        cams.append(
            Camera(
                R=mx.array(R.astype(np.float32)),
                t=mx.array(t.astype(np.float32)),
                fx=f_full,
                fy=f_full,
                cx=rec.K[0, 2] * inv_scale,
                cy=rec.K[1, 2] * inv_scale,
                width=orig_w,
                height=orig_h,
            )
        )
        names.append(os.path.basename(image_paths[img]))

    pids = [pid for pid in range(len(rec.points)) if len(rec.point_obs[pid]) >= 2]
    xyz = np.array([rec.points[p] for p in pids]).reshape(-1, 3)
    col = np.empty((len(pids), 3))
    for k, p in enumerate(pids):
        img = min(rec.point_obs[p])  # color from the first observing image
        col[k] = rec.kp_colors[img][rec.point_obs[p][img]]
    errors = np.array([rec.reproj_errors(p) for p in pids])
    sparse_dir = save_colmap(out_root, cams, names, xyz, col, point_errors=errors)
    mean_err = float(errors.mean()) if len(errors) else 0.0
    log(
        f"  SfM done: {len(registered)} cameras, {len(pids)} points, "
        f"mean reprojection {mean_err:.2f} px, focal {f_full:.0f} px"
    )
    return SfmResult(
        sparse_dir=sparse_dir,
        registered=names,
        num_points=len(pids),
        mean_reproj_px=mean_err,
    )