junaid-simamdigital commited on
Commit
c368fd5
·
verified ·
1 Parent(s): ebc7b33

eval: add COLMAP manifest importer

Browse files
Files changed (1) hide show
  1. import_colmap.py +116 -0
import_colmap.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert COLMAP text-model cameras/images into a Simam3D capture manifest."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+
12
+
13
+ def _records(path: Path):
14
+ for raw in path.read_text(encoding="utf-8").splitlines():
15
+ line = raw.strip()
16
+ if line and not line.startswith("#"):
17
+ yield line.split()
18
+
19
+
20
+ def _image_records(path: Path):
21
+ """Yield COLMAP image headers while skipping each observation line."""
22
+ lines = path.read_text(encoding="utf-8").splitlines()
23
+ index = 0
24
+ while index < len(lines):
25
+ line = lines[index].strip()
26
+ if not line or line.startswith("#"):
27
+ index += 1
28
+ continue
29
+ fields = line.split()
30
+ if len(fields) < 10:
31
+ raise ValueError("invalid COLMAP image record")
32
+ yield fields
33
+ index += 2
34
+
35
+
36
+ def _camera_matrix(fields: list[str]) -> np.ndarray:
37
+ model = fields[1]
38
+ width, height = int(fields[2]), int(fields[3])
39
+ params = [float(value) for value in fields[4:]]
40
+ if model in {"SIMPLE_PINHOLE", "SIMPLE_RADIAL", "RADIAL"}:
41
+ focal, cx, cy = params[:3]
42
+ fx = fy = focal
43
+ elif model in {"PINHOLE", "OPENCV", "OPENCV_FISHEYE", "FULL_OPENCV"}:
44
+ fx, fy, cx, cy = params[:4]
45
+ else:
46
+ raise ValueError(f"unsupported COLMAP camera model: {model}")
47
+ return np.array([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]], dtype=float), width, height
48
+
49
+
50
+ def _quaternion_rotation(qw: float, qx: float, qy: float, qz: float) -> np.ndarray:
51
+ norm = np.linalg.norm([qw, qx, qy, qz])
52
+ if norm <= 1e-12:
53
+ raise ValueError("COLMAP quaternion is zero")
54
+ qw, qx, qy, qz = np.asarray([qw, qx, qy, qz], dtype=float) / norm
55
+ return np.array([
56
+ [1 - 2 * (qy * qy + qz * qz), 2 * (qx * qy - qz * qw), 2 * (qx * qz + qy * qw)],
57
+ [2 * (qx * qy + qz * qw), 1 - 2 * (qx * qx + qz * qz), 2 * (qy * qz - qx * qw)],
58
+ [2 * (qx * qz - qy * qw), 2 * (qy * qz + qx * qw), 1 - 2 * (qx * qx + qy * qy)],
59
+ ])
60
+
61
+
62
+ def import_colmap(cameras_path: str | Path, images_path: str | Path, image_root: str | Path, held_out: set[str] | None = None) -> dict[str, object]:
63
+ cameras = {}
64
+ for fields in _records(Path(cameras_path)):
65
+ matrix, width, height = _camera_matrix(fields)
66
+ cameras[int(fields[0])] = (matrix, width, height)
67
+ image_root = Path(image_root)
68
+ held_out = held_out or set()
69
+ views = []
70
+ for fields in _image_records(Path(images_path)):
71
+ image_id, qw, qx, qy, qz, tx, ty, tz, camera_id = fields[:9]
72
+ name = " ".join(fields[9:])
73
+ if int(camera_id) not in cameras:
74
+ raise ValueError(f"image {image_id} references missing camera {camera_id}")
75
+ matrix, width, height = cameras[int(camera_id)]
76
+ extrinsics = np.eye(4, dtype=float)
77
+ extrinsics[:3, :3] = _quaternion_rotation(float(qw), float(qx), float(qy), float(qz))
78
+ extrinsics[:3, 3] = [float(tx), float(ty), float(tz)]
79
+ relative_image = Path(name)
80
+ absolute_image = image_root / relative_image
81
+ view = {
82
+ "id": str(image_id),
83
+ "image": relative_image.as_posix(),
84
+ "split": "held_out" if name in held_out or str(image_id) in held_out else "train",
85
+ "width": width,
86
+ "height": height,
87
+ "intrinsics": matrix.tolist(),
88
+ "extrinsics": extrinsics.tolist(),
89
+ }
90
+ if absolute_image.is_file():
91
+ view["sha256"] = hashlib.sha256(absolute_image.read_bytes()).hexdigest()
92
+ views.append(view)
93
+ return {
94
+ "project": "Simam3D",
95
+ "dataset": "COLMAP text model",
96
+ "coordinate_convention": "right-handed; extrinsics are world-to-camera",
97
+ "views": views,
98
+ }
99
+
100
+
101
+ def main(argv: list[str] | None = None) -> int:
102
+ parser = argparse.ArgumentParser(description=__doc__)
103
+ parser.add_argument("cameras", type=Path)
104
+ parser.add_argument("images", type=Path)
105
+ parser.add_argument("image_root", type=Path)
106
+ parser.add_argument("output", type=Path)
107
+ parser.add_argument("--held-out", nargs="*", default=[])
108
+ args = parser.parse_args(argv)
109
+ manifest = import_colmap(args.cameras, args.images, args.image_root, set(args.held_out))
110
+ args.output.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
111
+ print(f"wrote {args.output} with {len(manifest['views'])} views")
112
+ return 0
113
+
114
+
115
+ if __name__ == "__main__":
116
+ raise SystemExit(main())