from __future__ import annotations import argparse import json import shutil import time from pathlib import Path import pycolmap def main() -> None: parser = argparse.ArgumentParser(description="Refine a sequential phone capture with COLMAP SfM") parser.add_argument("images", type=Path) parser.add_argument("output", type=Path) parser.add_argument("--matching", choices=["sequential", "exhaustive"], default="sequential") args = parser.parse_args() source = args.images.resolve() source_images = sorted(p for p in source.iterdir() if p.is_file() and p.suffix.lower() in {".jpg", ".jpeg", ".png"}) if len(source_images) < 2: raise SystemExit("At least two JPEG/PNG input images required") output = args.output.resolve() images = output / "images" sparse = output / "sparse" database = output / "database.db" if database.exists() or sparse.exists(): raise SystemExit(f"refusing to overwrite an existing COLMAP run: {output}") images.mkdir(parents=True, exist_ok=True) sparse.mkdir(parents=True, exist_ok=True) for path in source_images: shutil.copy2(path, images / path.name) started = time.perf_counter() reader = pycolmap.ImageReaderOptions() reader.camera_model = "OPENCV" pycolmap.extract_features( database_path=database, image_path=images, camera_mode=pycolmap.CameraMode.SINGLE, reader_options=reader, device=pycolmap.Device.cpu, ) if args.matching == "exhaustive": pycolmap.match_exhaustive(database_path=database, device=pycolmap.Device.cpu) else: pycolmap.match_sequential(database_path=database, device=pycolmap.Device.cpu) reconstructions = pycolmap.incremental_mapping( database_path=database, image_path=images, output_path=sparse, ) if not reconstructions: raise SystemExit("COLMAP did not produce a reconstruction") best_id, best = max(reconstructions.items(), key=lambda item: len(item[1].images)) input_names = sorted(p.name for p in source_images) registered_names = sorted(image.name for image in best.images.values()) missing_names = sorted(set(input_names) - set(registered_names)) summary = { "schema": "kineworld.spatial0.colmap.v1", "pycolmap": pycolmap.__version__, "device": "cpu", "camera_mode": "SINGLE", "camera_model": "OPENCV", "input_images": len(input_names), "models": len(reconstructions), "matching": args.matching, "registration_status": "complete" if not missing_names else "partial", "registration_coverage": len(registered_names) / len(input_names), "unregistered_images": missing_names, "selected_model": best_id, "registered_images": len(best.images), "points3D": len(best.points3D), "elapsed_seconds": time.perf_counter() - started, } (output / "colmap-run.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") print(json.dumps(summary, indent=2)) if __name__ == "__main__": main()