COLMAP¶
Visualize COLMAP sparse reconstruction outputs. To get demo data, see ../assets/download_assets.sh.
Features:
COLMAP sparse reconstruction file parsing
Camera frustum visualization with
viser.SceneApi.add_camera_frustum()3D point cloud display from structure-from-motion
Interactive camera and point visibility controls
Note
This example requires external assets. To download them, run:
git clone -b v1.0.30 https://github.com/viser-project/viser.git
cd viser/examples
./assets/download_assets.sh
python 04_demos/01_colmap_visualizer.py # With viser installed.
Source: examples/04_demos/01_colmap_visualizer.py
Code¶
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 server = viser.ViserServer()
27 server.gui.configure_theme(titlebar_content=None)
28 server.gui.main_panel.dock_right()
29
30 # Load the colmap info.
31 cameras = read_cameras_binary(colmap_path / "cameras.bin")
32 images = read_images_binary(colmap_path / "images.bin")
33 points3d = read_points3d_binary(colmap_path / "points3D.bin")
34
35 points = np.array([points3d[p_id].xyz for p_id in points3d])
36 colors = np.array([points3d[p_id].rgb for p_id in points3d])
37
38 # Let's rotate the scene so the average camera direction is pointing up.
39 if reorient_scene:
40 average_up = (
41 # `qvec` corresponds to T_camera_world; we convert to T_world_camera.
42 vtf.SO3(np.array([img.qvec for img in images.values()])).inverse()
43 @ np.array([0.0, -1.0, 0.0]) # -y is up in the local frame!
44 ).mean(axis=0)
45 average_up /= np.linalg.norm(average_up)
46 server.scene.set_up_direction((average_up[0], average_up[1], average_up[2]))
47
48 gui_points = server.gui.add_slider(
49 "Max points",
50 min=1,
51 max=len(points3d),
52 step=1,
53 initial_value=min(len(points3d), 50_000),
54 )
55 gui_frames = server.gui.add_slider(
56 "Max frames",
57 min=1,
58 max=len(images),
59 step=1,
60 initial_value=min(len(images), 50),
61 )
62 gui_point_size = server.gui.add_slider(
63 "Point size", min=0.01, max=0.1, step=0.001, initial_value=0.02
64 )
65
66 point_mask = np.random.choice(points.shape[0], gui_points.value, replace=False)
67 point_cloud = server.scene.add_point_cloud(
68 name="/colmap/pcd",
69 points=points[point_mask],
70 colors=colors[point_mask],
71 point_size=gui_point_size.value,
72 )
73 frames: List[viser.FrameHandle] = []
74
75 def visualize_frames() -> None:
76
77 # Remove existing image frames.
78 for frame in frames:
79 frame.remove()
80 frames.clear()
81
82 # Interpret the images and cameras.
83 img_ids = [im.id for im in images.values()]
84 random.shuffle(img_ids)
85 img_ids = sorted(img_ids[: gui_frames.value])
86
87 for img_id in tqdm(img_ids):
88 img = images[img_id]
89 cam = cameras[img.camera_id]
90
91 # Skip images that don't exist.
92 image_filename = images_path / img.name
93 if not image_filename.exists():
94 continue
95
96 T_world_camera = vtf.SE3.from_rotation_and_translation(
97 vtf.SO3(img.qvec), img.tvec
98 ).inverse()
99 frame = server.scene.add_frame(
100 f"/colmap/frame_{img_id}",
101 wxyz=T_world_camera.rotation().wxyz,
102 position=T_world_camera.translation(),
103 axes_length=0.1,
104 axes_radius=0.005,
105 )
106 frames.append(frame)
107
108 # For pinhole cameras, cam.params will be (fx, fy, cx, cy).
109 if cam.model != "PINHOLE":
110 print(f"Expected pinhole camera, but got {cam.model}")
111
112 H, W = cam.height, cam.width
113 fy = cam.params[1]
114 image = iio.imread(image_filename)
115 image = image[::downsample_factor, ::downsample_factor]
116 frustum = server.scene.add_camera_frustum(
117 f"/colmap/frame_{img_id}/frustum",
118 fov=2 * np.arctan2(H / 2, fy),
119 aspect=W / H,
120 scale=0.15,
121 image=image,
122 )
123
124 @frustum.on_click
125 def _(_, frame=frame) -> None:
126 for client in server.get_clients().values():
127 client.camera.wxyz = frame.wxyz
128 client.camera.position = frame.position
129
130 need_update = True
131
132 @gui_points.on_update
133 def _(_) -> None:
134 point_mask = np.random.choice(points.shape[0], gui_points.value, replace=False)
135 with server.atomic():
136 point_cloud.points = points[point_mask]
137 point_cloud.colors = colors[point_mask]
138
139 @gui_frames.on_update
140 def _(_) -> None:
141 nonlocal need_update
142 need_update = True
143
144 @gui_point_size.on_update
145 def _(_) -> None:
146 point_cloud.point_size = gui_point_size.value
147
148 while True:
149 if need_update:
150 need_update = False
151 visualize_frames()
152
153 time.sleep(1e-3)
154
155
156if __name__ == "__main__":
157 tyro.cli(main)