COLMAP visualizerΒΆ
Visualize COLMAP sparse reconstruction outputs. To get demo data, see ./assets/download_colmap_garden.sh
.
1import random
2import time
3from pathlib import Path
4from typing import List
5
6import imageio.v3 as iio
7import numpy as np
8import tyro
9from tqdm.auto import tqdm
10
11import viser
12import viser.transforms as vtf
13from viser.extras.colmap import (
14 read_cameras_binary,
15 read_images_binary,
16 read_points3d_binary,
17)
18
19
20def main(
21 colmap_path: Path = Path(__file__).parent / "assets/colmap_garden/sparse/0",
22 images_path: Path = Path(__file__).parent / "assets/colmap_garden/images_8",
23 downsample_factor: int = 2,
24 reorient_scene: bool = True,
25) -> None:
26 """Visualize COLMAP sparse reconstruction outputs.
27
28 Args:
29 colmap_path: Path to the COLMAP reconstruction directory.
30 images_path: Path to the COLMAP images directory.
31 downsample_factor: Downsample factor for the images.
32 """
33 server = viser.ViserServer()
34 server.gui.configure_theme(titlebar_content=None, control_layout="collapsible")
35
36 # Load the colmap info.
37 cameras = read_cameras_binary(colmap_path / "cameras.bin")
38 images = read_images_binary(colmap_path / "images.bin")
39 points3d = read_points3d_binary(colmap_path / "points3D.bin")
40
41 points = np.array([points3d[p_id].xyz for p_id in points3d])
42 colors = np.array([points3d[p_id].rgb for p_id in points3d])
43
44 gui_reset_up = server.gui.add_button(
45 "Reset up direction",
46 hint="Set the camera control 'up' direction to the current camera's 'up'.",
47 )
48
49 # Let's rotate the scene so the average camera direction is pointing up.
50 if reorient_scene:
51 average_up = (
52 vtf.SO3(np.array([img.qvec for img in images.values()]))
53 @ np.array([0.0, -1.0, 0.0]) # -y is up in the local frame!
54 ).mean(axis=0)
55 average_up /= np.linalg.norm(average_up)
56 server.scene.set_up_direction((average_up[0], average_up[1], average_up[2]))
57
58 @gui_reset_up.on_click
59 def _(event: viser.GuiEvent) -> None:
60 client = event.client
61 assert client is not None
62 client.camera.up_direction = vtf.SO3(client.camera.wxyz) @ np.array(
63 [0.0, -1.0, 0.0]
64 )
65
66 gui_points = server.gui.add_slider(
67 "Max points",
68 min=1,
69 max=len(points3d),
70 step=1,
71 initial_value=min(len(points3d), 50_000),
72 )
73 gui_frames = server.gui.add_slider(
74 "Max frames",
75 min=1,
76 max=len(images),
77 step=1,
78 initial_value=min(len(images), 100),
79 )
80 gui_point_size = server.gui.add_slider(
81 "Point size", min=0.01, max=0.1, step=0.001, initial_value=0.05
82 )
83
84 point_mask = np.random.choice(points.shape[0], gui_points.value, replace=False)
85 point_cloud = server.scene.add_point_cloud(
86 name="/colmap/pcd",
87 points=points[point_mask],
88 colors=colors[point_mask],
89 point_size=gui_point_size.value,
90 )
91 frames: List[viser.FrameHandle] = []
92
93 def visualize_frames() -> None:
94 """Send all COLMAP elements to viser for visualization. This could be optimized
95 a ton!"""
96
97 # Remove existing image frames.
98 for frame in frames:
99 frame.remove()
100 frames.clear()
101
102 # Interpret the images and cameras.
103 img_ids = [im.id for im in images.values()]
104 random.shuffle(img_ids)
105 img_ids = sorted(img_ids[: gui_frames.value])
106
107 for img_id in tqdm(img_ids):
108 img = images[img_id]
109 cam = cameras[img.camera_id]
110
111 # Skip images that don't exist.
112 image_filename = images_path / img.name
113 if not image_filename.exists():
114 continue
115
116 T_world_camera = vtf.SE3.from_rotation_and_translation(
117 vtf.SO3(img.qvec), img.tvec
118 ).inverse()
119 frame = server.scene.add_frame(
120 f"/colmap/frame_{img_id}",
121 wxyz=T_world_camera.rotation().wxyz,
122 position=T_world_camera.translation(),
123 axes_length=0.1,
124 axes_radius=0.005,
125 )
126 frames.append(frame)
127
128 # For pinhole cameras, cam.params will be (fx, fy, cx, cy).
129 if cam.model != "PINHOLE":
130 print(f"Expected pinhole camera, but got {cam.model}")
131
132 H, W = cam.height, cam.width
133 fy = cam.params[1]
134 image = iio.imread(image_filename)
135 image = image[::downsample_factor, ::downsample_factor]
136 frustum = server.scene.add_camera_frustum(
137 f"/colmap/frame_{img_id}/frustum",
138 fov=2 * np.arctan2(H / 2, fy),
139 aspect=W / H,
140 scale=0.15,
141 image=image,
142 )
143
144 @frustum.on_click
145 def _(_, frame=frame) -> None:
146 for client in server.get_clients().values():
147 client.camera.wxyz = frame.wxyz
148 client.camera.position = frame.position
149
150 need_update = True
151
152 @gui_points.on_update
153 def _(_) -> None:
154 point_mask = np.random.choice(points.shape[0], gui_points.value, replace=False)
155 with server.atomic():
156 point_cloud.points = points[point_mask]
157 point_cloud.colors = colors[point_mask]
158
159 @gui_frames.on_update
160 def _(_) -> None:
161 nonlocal need_update
162 need_update = True
163
164 @gui_point_size.on_update
165 def _(_) -> None:
166 point_cloud.point_size = gui_point_size.value
167
168 while True:
169 if need_update:
170 need_update = False
171 visualize_frames()
172
173 time.sleep(1e-3)
174
175
176if __name__ == "__main__":
177 tyro.cli(main)