| 1 |
"""Structure-from-Motion pipelines for 360-degree panorama images.""" |
| 2 |
|
| 3 |
import collections |
| 4 |
import enum |
| 5 |
import os |
| 6 |
import sys |
| 7 |
from collections.abc import Callable, Sequence |
| 8 |
from concurrent.futures import ThreadPoolExecutor, as_completed |
| 9 |
from dataclasses import dataclass |
| 10 |
from pathlib import Path |
| 11 |
from threading import Lock |
| 12 |
from typing import Literal, TypeVar, cast |
| 13 |
|
| 14 |
import numpy as np |
| 15 |
import numpy.typing as npt |
| 16 |
|
| 17 |
from . import _core as pycolmap |
| 18 |
|
| 19 |
logging = pycolmap.logging |
| 20 |
|
| 21 |
|
| 22 |
if sys.version_info >= (3, 11): |
| 23 |
StrEnum = enum.StrEnum |
| 24 |
else: |
| 25 |
# Backport of enum.StrEnum, added in Python 3.11. Members compare equal to |
| 26 |
# their string value and auto() yields the lower-cased member name. |
| 27 |
# TODO: remove once support for Python 3.10 is dropped after its EOL in |
| 28 |
# October 2026. |
| 29 |
class StrEnum(str, enum.Enum): |
| 30 |
@staticmethod |
| 31 |
def _generate_next_value_( |
| 32 |
name: str, start: int, count: int, last_values: list |
| 33 |
) -> str: |
| 34 |
return name.lower() |
| 35 |
|
| 36 |
def __str__(self) -> str: |
| 37 |
return str(self.value) |
| 38 |
|
| 39 |
|
| 40 |
class Matcher(StrEnum): |
| 41 |
SEQUENTIAL = enum.auto() |
| 42 |
EXHAUSTIVE = enum.auto() |
| 43 |
VOCABTREE = enum.auto() |
| 44 |
SPATIAL = enum.auto() |
| 45 |
|
| 46 |
|
| 47 |
class Mapper(StrEnum): |
| 48 |
INCREMENTAL = enum.auto() |
| 49 |
GLOBAL = enum.auto() |
| 50 |
|
| 51 |
|
| 52 |
class PanoRenderType(StrEnum): |
| 53 |
PERSPECTIVE_OVERLAPPING = enum.auto() |
| 54 |
PERSPECTIVE_NON_OVERLAPPING = enum.auto() |
| 55 |
# Reconstruct directly on the panoramas with the native EQUIRECTANGULAR |
| 56 |
# camera model instead of rendering perspective images. |
| 57 |
SPHERICAL = enum.auto() |
| 58 |
|
| 59 |
|
| 60 |
N = TypeVar("N", bound=int) |
| 61 |
NDArrayNx2 = np.ndarray[tuple[N, Literal[2]], np.dtype[np.float64]] |
| 62 |
NDArray3x1 = np.ndarray[tuple[Literal[3], Literal[1]], np.dtype[np.float64]] |
| 63 |
NDArray3x3 = np.ndarray[tuple[Literal[3], Literal[3]], np.dtype[np.float64]] |
| 64 |
|
| 65 |
|
| 66 |
@dataclass(kw_only=True) |
| 67 |
class PanoRenderOptions: |
| 68 |
num_steps_yaw: int |
| 69 |
pitches_deg: Sequence[float] |
| 70 |
hfov_deg: float |
| 71 |
vfov_deg: float |
| 72 |
|
| 73 |
|
| 74 |
PANO_RENDER_OPTIONS: dict[PanoRenderType, PanoRenderOptions] = { |
| 75 |
PanoRenderType.PERSPECTIVE_OVERLAPPING: PanoRenderOptions( |
| 76 |
num_steps_yaw=4, |
| 77 |
pitches_deg=(-35.0, 0.0, 35.0), |
| 78 |
hfov_deg=90.0, |
| 79 |
vfov_deg=90.0, |
| 80 |
), |
| 81 |
# Cubemap without top and bottom images. |
| 82 |
PanoRenderType.PERSPECTIVE_NON_OVERLAPPING: PanoRenderOptions( |
| 83 |
num_steps_yaw=4, |
| 84 |
pitches_deg=(0.0,), |
| 85 |
hfov_deg=90.0, |
| 86 |
vfov_deg=90.0, |
| 87 |
), |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
@dataclass(kw_only=True) |
| 92 |
class PanoramaReconstructionOptions: |
| 93 |
matcher: Matcher = Matcher.SEQUENTIAL |
| 94 |
mapper: Mapper = Mapper.INCREMENTAL |
| 95 |
render_type: PanoRenderType = PanoRenderType.PERSPECTIVE_OVERLAPPING |
| 96 |
random_seed: int = 0 |
| 97 |
num_threads: int = -1 |
| 98 |
gpu_index: str = "-1" |
| 99 |
use_gpu: bool = True |
| 100 |
covisibility_path: Path | None = None |
| 101 |
covisibility_min_shared_points: int = 1 |
| 102 |
show_progress: bool = True |
| 103 |
|
| 104 |
|
| 105 |
def create_virtual_camera( |
| 106 |
*, |
| 107 |
pano_width: int, |
| 108 |
pano_height: int, |
| 109 |
hfov_deg: float, |
| 110 |
vfov_deg: float, |
| 111 |
) -> pycolmap.Camera: |
| 112 |
"""Create a virtual perspective camera.""" |
| 113 |
image_width = int(pano_width * hfov_deg / 360) |
| 114 |
image_height = int(pano_height * vfov_deg / 180) |
| 115 |
focal = image_width / (2 * np.tan(np.deg2rad(hfov_deg) / 2)) |
| 116 |
camera = pycolmap.Camera.create_from_model_id( |
| 117 |
camera_id=0, |
| 118 |
model=pycolmap.CameraModelId.SIMPLE_PINHOLE, |
| 119 |
focal_length=focal, |
| 120 |
width=image_width, |
| 121 |
height=image_height, |
| 122 |
) |
| 123 |
# Not set by create_from_model_id. |
| 124 |
camera.has_prior_focal_length = True |
| 125 |
return camera |
| 126 |
|
| 127 |
|
| 128 |
def get_virtual_camera_rays( |
| 129 |
camera: pycolmap.Camera, |
| 130 |
) -> npt.NDArray[np.floating]: |
| 131 |
size = (camera.width, camera.height) |
| 132 |
x, y = np.indices(size).astype(np.float32) |
| 133 |
xy: NDArrayNx2 = np.column_stack([x.ravel(), y.ravel()]) |
| 134 |
# The center of the upper left most pixel has coordinate (0.5, 0.5) |
| 135 |
xy += 0.5 |
| 136 |
xy_norm: NDArrayNx2 = camera.cam_from_img(image_points=xy) |
| 137 |
rays = np.concatenate([xy_norm, np.ones_like(xy_norm[:, :1])], -1) |
| 138 |
rays /= np.linalg.norm(rays, axis=-1, keepdims=True) |
| 139 |
return rays |
| 140 |
|
| 141 |
|
| 142 |
def spherical_img_from_cam( |
| 143 |
image_size: tuple[int, int], rays_in_cam: npt.NDArray[np.floating] |
| 144 |
) -> npt.NDArray[np.floating]: |
| 145 |
"""Project rays into a 360 panorama (spherical) image.""" |
| 146 |
if image_size[0] != image_size[1] * 2: |
| 147 |
raise ValueError("Only 360° panoramas are supported.") |
| 148 |
if rays_in_cam.ndim != 2 or rays_in_cam.shape[1] != 3: |
| 149 |
raise ValueError(f"{rays_in_cam.shape=} but expected (N,3).") |
| 150 |
r = rays_in_cam.T |
| 151 |
yaw = np.arctan2(r[0], r[2]) |
| 152 |
pitch = -np.arctan2(r[1], np.linalg.norm(r[[0, 2]], axis=0)) |
| 153 |
u = (1 + yaw / np.pi) / 2 |
| 154 |
v = (1 - pitch * 2 / np.pi) / 2 |
| 155 |
return np.stack([u, v], -1) * image_size |
| 156 |
|
| 157 |
|
| 158 |
def get_virtual_rotations( |
| 159 |
num_steps_yaw: int, pitches_deg: Sequence[float] |
| 160 |
) -> Sequence[npt.NDArray[np.floating]]: |
| 161 |
"""Get the relative rotations of the virtual cameras w.r.t. the panorama.""" |
| 162 |
# Assuming that the panos are approximately upright. |
| 163 |
cams_from_pano_r = [] |
| 164 |
yaws = np.linspace(0, 360, num_steps_yaw, endpoint=False) |
| 165 |
for pitch_deg in pitches_deg: |
| 166 |
yaw_offset = (360 / num_steps_yaw / 2) if pitch_deg > 0 else 0 |
| 167 |
for yaw_deg in yaws + yaw_offset: |
| 168 |
pitch, yaw = np.deg2rad([-pitch_deg, -yaw_deg]) |
| 169 |
cos_pitch, sin_pitch = np.cos(pitch), np.sin(pitch) |
| 170 |
cos_yaw, sin_yaw = np.cos(yaw), np.sin(yaw) |
| 171 |
rotation_x = np.array( |
| 172 |
[ |
| 173 |
[1.0, 0.0, 0.0], |
| 174 |
[0.0, cos_pitch, -sin_pitch], |
| 175 |
[0.0, sin_pitch, cos_pitch], |
| 176 |
] |
| 177 |
) |
| 178 |
rotation_y = np.array( |
| 179 |
[ |
| 180 |
[cos_yaw, 0.0, sin_yaw], |
| 181 |
[0.0, 1.0, 0.0], |
| 182 |
[-sin_yaw, 0.0, cos_yaw], |
| 183 |
] |
| 184 |
) |
| 185 |
cam_from_pano_r = rotation_x @ rotation_y |
| 186 |
cams_from_pano_r.append(cam_from_pano_r) |
| 187 |
return cams_from_pano_r |
| 188 |
|
| 189 |
|
| 190 |
def create_pano_rig_config( |
| 191 |
cams_from_pano_rotation: Sequence[npt.NDArray[np.floating]], |
| 192 |
ref_idx: int = 0, |
| 193 |
) -> pycolmap.RigConfig: |
| 194 |
"""Create a RigConfig for the given virtual rotations.""" |
| 195 |
rig_cameras = [] |
| 196 |
zero_translation = cast(NDArray3x1, np.zeros((3, 1), dtype=np.float64)) |
| 197 |
for idx, cam_from_pano_rotation in enumerate(cams_from_pano_rotation): |
| 198 |
if idx == ref_idx: |
| 199 |
cam_from_rig = None |
| 200 |
else: |
| 201 |
cam_from_ref_rotation = ( |
| 202 |
cam_from_pano_rotation @ cams_from_pano_rotation[ref_idx].T |
| 203 |
) |
| 204 |
cam_from_rig = pycolmap.Rigid3d( |
| 205 |
pycolmap.Rotation3d(cam_from_ref_rotation), |
| 206 |
zero_translation, |
| 207 |
) |
| 208 |
rig_cameras.append( |
| 209 |
pycolmap.RigConfigCamera( |
| 210 |
ref_sensor=idx == ref_idx, |
| 211 |
image_prefix=f"pano_camera{idx}/", |
| 212 |
cam_from_rig=cam_from_rig, |
| 213 |
) |
| 214 |
) |
| 215 |
return pycolmap.RigConfig(cameras=rig_cameras) |
| 216 |
|
| 217 |
|
| 218 |
class PanoProcessor: |
| 219 |
def __init__( |
| 220 |
self, |
| 221 |
pano_image_dir: Path, |
| 222 |
output_image_dir: Path, |
| 223 |
mask_dir: Path, |
| 224 |
render_options: PanoRenderOptions, |
| 225 |
): |
| 226 |
self.render_options = render_options |
| 227 |
self.pano_image_dir = pano_image_dir |
| 228 |
self.output_image_dir = output_image_dir |
| 229 |
self.mask_dir = mask_dir |
| 230 |
|
| 231 |
self.cams_from_pano_rotation = get_virtual_rotations( |
| 232 |
num_steps_yaw=render_options.num_steps_yaw, |
| 233 |
pitches_deg=render_options.pitches_deg, |
| 234 |
) |
| 235 |
self.rig_config = create_pano_rig_config(self.cams_from_pano_rotation) |
| 236 |
|
| 237 |
# We assign each pano pixel to the virtual camera |
| 238 |
# with the closest camera center. |
| 239 |
self.cam_centers_in_pano = np.einsum( |
| 240 |
"nij,i->nj", self.cams_from_pano_rotation, [0, 0, 1] |
| 241 |
) |
| 242 |
|
| 243 |
self._lock = Lock() |
| 244 |
|
| 245 |
# These are initialized on the first pano image |
| 246 |
# to avoid recomputing the rays for each pano image. |
| 247 |
self._camera: pycolmap.Camera | None = None |
| 248 |
self._pano_size: tuple[int, int] | None = None |
| 249 |
self._rays_in_cam: npt.NDArray[np.floating] | None = None |
| 250 |
|
| 251 |
def process(self, pano_name: str) -> None: |
| 252 |
import cv2 |
| 253 |
import PIL.ExifTags |
| 254 |
import PIL.Image |
| 255 |
|
| 256 |
pano_path = self.pano_image_dir / pano_name |
| 257 |
try: |
| 258 |
pano_pil_image = PIL.Image.open(pano_path) |
| 259 |
except PIL.Image.UnidentifiedImageError: |
| 260 |
logging.info(f"Skipping file {pano_path} as it cannot be read.") |
| 261 |
return |
| 262 |
|
| 263 |
pano_exif = pano_pil_image.getexif() |
| 264 |
gpsonly_exif = PIL.Image.Exif() |
| 265 |
gpsonly_exif[PIL.ExifTags.IFD.GPSInfo] = pano_exif.get_ifd( |
| 266 |
PIL.ExifTags.IFD.GPSInfo |
| 267 |
) |
| 268 |
|
| 269 |
pano_image = np.asarray(pano_pil_image) |
| 270 |
pano_height, pano_width, *_ = pano_image.shape |
| 271 |
if pano_width != pano_height * 2: |
| 272 |
raise ValueError("Only 360° panoramas are supported.") |
| 273 |
|
| 274 |
with self._lock: |
| 275 |
if self._camera is None: # First image, precompute rays once. |
| 276 |
self._camera = create_virtual_camera( |
| 277 |
pano_width=pano_width, |
| 278 |
pano_height=pano_height, |
| 279 |
hfov_deg=self.render_options.hfov_deg, |
| 280 |
vfov_deg=self.render_options.vfov_deg, |
| 281 |
) |
| 282 |
for rig_camera in self.rig_config.cameras: |
| 283 |
rig_camera.camera = self._camera |
| 284 |
self._pano_size = (pano_width, pano_height) |
| 285 |
self._rays_in_cam = get_virtual_camera_rays(self._camera) |
| 286 |
else: # Later images, verify consistent panoramas. |
| 287 |
if (pano_width, pano_height) != self._pano_size: |
| 288 |
raise ValueError( |
| 289 |
"Panoramas of different sizes are not supported." |
| 290 |
) |
| 291 |
|
| 292 |
for cam_idx, cam_from_pano_r in enumerate(self.cams_from_pano_rotation): |
| 293 |
assert self._rays_in_cam is not None |
| 294 |
rays_in_pano = self._rays_in_cam @ cam_from_pano_r |
| 295 |
xy_in_pano = spherical_img_from_cam(self._pano_size, rays_in_pano) |
| 296 |
xy_in_pano = xy_in_pano.reshape( |
| 297 |
self._camera.width, self._camera.height, 2 |
| 298 |
).astype(np.float32) |
| 299 |
xy_in_pano -= 0.5 # COLMAP to OpenCV pixel origin. |
| 300 |
x_coords, y_coords = np.moveaxis(xy_in_pano, [0, 1, 2], [2, 1, 0]) |
| 301 |
image = cv2.remap( |
| 302 |
pano_image, |
| 303 |
x_coords, |
| 304 |
y_coords, |
| 305 |
cv2.INTER_LINEAR, |
| 306 |
borderMode=cv2.BORDER_WRAP, |
| 307 |
) |
| 308 |
# We define a mask such that each pixel of the panorama has its |
| 309 |
# features extracted only in a single virtual camera. |
| 310 |
closest_camera = np.argmax( |
| 311 |
rays_in_pano @ self.cam_centers_in_pano.T, -1 |
| 312 |
) |
| 313 |
mask = ( |
| 314 |
((closest_camera == cam_idx) * 255) |
| 315 |
.astype(np.uint8) |
| 316 |
.reshape(self._camera.width, self._camera.height) |
| 317 |
.transpose() |
| 318 |
) |
| 319 |
|
| 320 |
image_name = ( |
| 321 |
self.rig_config.cameras[cam_idx].image_prefix + pano_name |
| 322 |
) |
| 323 |
mask_name = f"{image_name}.png" |
| 324 |
|
| 325 |
image_path = self.output_image_dir / image_name |
| 326 |
image_path.parent.mkdir(exist_ok=True, parents=True) |
| 327 |
PIL.Image.fromarray(image).save(image_path, exif=gpsonly_exif) |
| 328 |
|
| 329 |
mask_path = self.mask_dir / mask_name |
| 330 |
mask_path.parent.mkdir(exist_ok=True, parents=True) |
| 331 |
if not pycolmap.Bitmap.from_array(mask).write(mask_path): |
| 332 |
raise RuntimeError(f"Cannot write {mask_path}") |
| 333 |
|
| 334 |
def split_image_name(self, image_name: str) -> tuple[int, str]: |
| 335 |
"""Split a rendered image name into (virtual camera idx, pano name).""" |
| 336 |
for cam_idx, rig_camera in enumerate(self.rig_config.cameras): |
| 337 |
prefix = rig_camera.image_prefix |
| 338 |
if image_name.startswith(prefix): |
| 339 |
return cam_idx, image_name[len(prefix) :] |
| 340 |
raise ValueError(f"Unknown virtual camera for image {image_name!r}.") |
| 341 |
|
| 342 |
def convert_to_equirectangular( |
| 343 |
self, reconstruction: pycolmap.Reconstruction |
| 344 |
) -> pycolmap.Reconstruction: |
| 345 |
"""Convert a reconstruction built from the rig of perspective virtual |
| 346 |
cameras back to one equirectangular camera/image per input panorama. |
| 347 |
|
| 348 |
The output reconstruction references the original panorama images with |
| 349 |
the native EQUIRECTANGULAR camera model. Frame poses, 3D points, and |
| 350 |
all keypoints (including those without a 3D observation) are carried |
| 351 |
over by re-projecting the perspective keypoints onto the panorama |
| 352 |
through the same spherical mapping used for rendering, so the result is |
| 353 |
a valid, bundle-adjustable reconstruction. |
| 354 |
""" |
| 355 |
if self._camera is None or self._pano_size is None: |
| 356 |
raise RuntimeError("No panorama was rendered yet.") |
| 357 |
pano_width, pano_height = self._pano_size |
| 358 |
|
| 359 |
equirect = pycolmap.Reconstruction() |
| 360 |
equirect_camera = pycolmap.Camera.create_from_model_id( |
| 361 |
camera_id=1, |
| 362 |
model=pycolmap.CameraModelId.EQUIRECTANGULAR, |
| 363 |
focal_length=0.0, |
| 364 |
width=pano_width, |
| 365 |
height=pano_height, |
| 366 |
) |
| 367 |
equirect.add_camera_with_trivial_rig(equirect_camera) |
| 368 |
|
| 369 |
# The rig reference sensor is virtual camera 0 (see |
| 370 |
# create_pano_rig_config), so rig_from_world == cam0_from_world and |
| 371 |
# pano_from_world = pano_from_cam0 @ cam0_from_world. The virtual |
| 372 |
# cameras share the panorama center, hence the zero translation. |
| 373 |
pano_from_ref = pycolmap.Rigid3d( |
| 374 |
pycolmap.Rotation3d( |
| 375 |
cast(NDArray3x3, self.cams_from_pano_rotation[0]) |
| 376 |
), |
| 377 |
cast(NDArray3x1, np.zeros((3, 1), dtype=np.float64)), |
| 378 |
).inverse() |
| 379 |
|
| 380 |
# Group the registered virtual cameras by frame. All virtual cameras of |
| 381 |
# a frame observe the same panorama and share its pose, so we can |
| 382 |
# accumulate their keypoints into a single equirectangular image. |
| 383 |
images_by_frame: dict[int, list[pycolmap.Image]] = ( |
| 384 |
collections.defaultdict(list) |
| 385 |
) |
| 386 |
for image in reconstruction.images.values(): |
| 387 |
if image.has_pose: |
| 388 |
images_by_frame[image.frame_id].append(image) |
| 389 |
|
| 390 |
# Maps an image_id of a virtual camera to a dict from its old point2D |
| 391 |
# index to the (new point2D index, pano_name) in the equirectangular |
| 392 |
# image, so we can later rebuild the 3D point tracks. |
| 393 |
old_to_new_point2D: dict[int, dict[int, tuple[int, str]]] = {} |
| 394 |
pano_to_image_id: dict[str, int] = {} |
| 395 |
|
| 396 |
frame_images = sorted( |
| 397 |
images_by_frame.values(), |
| 398 |
key=lambda images: self.split_image_name(images[0].name)[1], |
| 399 |
) |
| 400 |
for image_id, images in enumerate(frame_images, start=1): |
| 401 |
pano_name = self.split_image_name(images[0].name)[1] |
| 402 |
pano_to_image_id[pano_name] = image_id |
| 403 |
frame = images[0].frame |
| 404 |
assert frame is not None |
| 405 |
rig_from_world = frame.rig_from_world |
| 406 |
assert rig_from_world is not None |
| 407 |
pano_from_world = pano_from_ref * rig_from_world |
| 408 |
|
| 409 |
# Concatenate the keypoints of all virtual cameras of this panorama. |
| 410 |
keypoints: list[npt.NDArray[np.floating]] = [] |
| 411 |
for image in images: |
| 412 |
cam_idx = self.split_image_name(image.name)[0] |
| 413 |
num_points2D = len(image.points2D) |
| 414 |
if num_points2D == 0: |
| 415 |
old_to_new_point2D[image.image_id] = {} |
| 416 |
continue |
| 417 |
# The cast is needed because numpy<2.3, the latest version |
| 418 |
# supporting Python 3.10, does not infer the array shape. |
| 419 |
# TODO: remove once support for Python 3.10 is dropped after |
| 420 |
# its EOL in October 2026. |
| 421 |
xy = cast( |
| 422 |
NDArrayNx2, |
| 423 |
np.array([point2D.xy for point2D in image.points2D]), |
| 424 |
) |
| 425 |
rays_in_cam: npt.NDArray[np.floating] = np.asarray( |
| 426 |
self._camera.cam_ray_from_img(image_points=xy) |
| 427 |
) |
| 428 |
rays_in_cam /= np.linalg.norm( |
| 429 |
rays_in_cam, axis=-1, keepdims=True |
| 430 |
) |
| 431 |
rays_in_pano = ( |
| 432 |
rays_in_cam @ self.cams_from_pano_rotation[cam_idx] |
| 433 |
) |
| 434 |
xy_in_pano = spherical_img_from_cam( |
| 435 |
self._pano_size, rays_in_pano |
| 436 |
) |
| 437 |
|
| 438 |
base_idx = len(keypoints) |
| 439 |
keypoints.extend(xy_in_pano) |
| 440 |
old_to_new_point2D[image.image_id] = { |
| 441 |
point2D_idx: (base_idx + point2D_idx, pano_name) |
| 442 |
for point2D_idx in range(num_points2D) |
| 443 |
} |
| 444 |
|
| 445 |
equirect.add_image_with_trivial_frame( |
| 446 |
pycolmap.Image( |
| 447 |
name=pano_name, |
| 448 |
keypoints=keypoints, |
| 449 |
camera_id=equirect_camera.camera_id, |
| 450 |
image_id=image_id, |
| 451 |
), |
| 452 |
pano_from_world, |
| 453 |
) |
| 454 |
|
| 455 |
for point3D_id, point3D in reconstruction.points3D.items(): |
| 456 |
track = pycolmap.Track() |
| 457 |
for element in point3D.track.elements: |
| 458 |
new_point2D_idx, pano_name = old_to_new_point2D[ |
| 459 |
element.image_id |
| 460 |
][element.point2D_idx] |
| 461 |
track.add_element(pano_to_image_id[pano_name], new_point2D_idx) |
| 462 |
equirect.add_point3D_with_id( |
| 463 |
point3D_id, |
| 464 |
pycolmap.Point3D( |
| 465 |
xyz=point3D.xyz, color=point3D.color, track=track |
| 466 |
), |
| 467 |
) |
| 468 |
|
| 469 |
return equirect |
| 470 |
|
| 471 |
|
| 472 |
def render_perspective_images( |
| 473 |
pano_image_names: Sequence[str], |
| 474 |
pano_image_dir: Path, |
| 475 |
output_image_dir: Path, |
| 476 |
mask_dir: Path, |
| 477 |
render_options: PanoRenderOptions, |
| 478 |
show_progress: bool, |
| 479 |
) -> PanoProcessor: |
| 480 |
processor = PanoProcessor( |
| 481 |
pano_image_dir, output_image_dir, mask_dir, render_options |
| 482 |
) |
| 483 |
|
| 484 |
num_panos = len(pano_image_names) |
| 485 |
max_workers = min(32, (os.cpu_count() or 2) - 1) |
| 486 |
|
| 487 |
pbar = None |
| 488 |
if show_progress: |
| 489 |
from tqdm import tqdm |
| 490 |
|
| 491 |
pbar = tqdm(total=num_panos) |
| 492 |
try: |
| 493 |
with ThreadPoolExecutor(max_workers=max_workers) as thread_pool: |
| 494 |
futures = [ |
| 495 |
thread_pool.submit(processor.process, pano_name) |
| 496 |
for pano_name in pano_image_names |
| 497 |
] |
| 498 |
for future in as_completed(futures): |
| 499 |
future.result() |
| 500 |
if pbar is not None: |
| 501 |
pbar.update(1) |
| 502 |
finally: |
| 503 |
if pbar is not None: |
| 504 |
pbar.close() |
| 505 |
|
| 506 |
return processor |
| 507 |
|
| 508 |
|
| 509 |
def run_matcher( |
| 510 |
options: PanoramaReconstructionOptions, |
| 511 |
database_path: Path, |
| 512 |
matching_options: pycolmap.FeatureMatchingOptions, |
| 513 |
) -> None: |
| 514 |
matching_options.use_gpu = options.use_gpu |
| 515 |
matching_options.gpu_index = options.gpu_index |
| 516 |
matching_options.num_threads = options.num_threads |
| 517 |
if options.matcher == Matcher.SEQUENTIAL: |
| 518 |
pycolmap.match_sequential( |
| 519 |
database_path, |
| 520 |
pairing_options=pycolmap.SequentialPairingOptions(), |
| 521 |
matching_options=matching_options, |
| 522 |
) |
| 523 |
elif options.matcher == Matcher.EXHAUSTIVE: |
| 524 |
pycolmap.match_exhaustive( |
| 525 |
database_path, matching_options=matching_options |
| 526 |
) |
| 527 |
elif options.matcher == Matcher.VOCABTREE: |
| 528 |
pycolmap.match_vocabtree( |
| 529 |
database_path, matching_options=matching_options |
| 530 |
) |
| 531 |
elif options.matcher == Matcher.SPATIAL: |
| 532 |
pycolmap.match_spatial(database_path, matching_options=matching_options) |
| 533 |
else: |
| 534 |
raise ValueError(f"Unknown matcher: {options.matcher}") |
| 535 |
|
| 536 |
|
| 537 |
def filter_database_by_covisibility( |
| 538 |
database_path: Path, |
| 539 |
covisibility_path: Path, |
| 540 |
min_shared_points: int, |
| 541 |
split_image_name: Callable[[str], tuple[int, str]] | None = None, |
| 542 |
) -> None: |
| 543 |
with np.load(covisibility_path) as covisibility: |
| 544 |
image_names = covisibility["image_names"].tolist() |
| 545 |
overlap_counts = covisibility["directed_overlap_counts"] |
| 546 |
image_name_to_idx = {name: idx for idx, name in enumerate(image_names)} |
| 547 |
|
| 548 |
def pano_name(image_name: str) -> str: |
| 549 |
if split_image_name is None: |
| 550 |
return image_name |
| 551 |
return split_image_name(image_name)[1] |
| 552 |
|
| 553 |
with pycolmap.Database.open(database_path) as database: |
| 554 |
database_image_names = { |
| 555 |
image.image_id: pano_name(image.name) |
| 556 |
for image in database.read_all_images() |
| 557 |
} |
| 558 |
pair_ids, _ = database.read_two_view_geometry_num_inliers() |
| 559 |
num_filtered = 0 |
| 560 |
for pair_id in pair_ids: |
| 561 |
image_id1, image_id2 = pycolmap.pair_id_to_image_pair(pair_id) |
| 562 |
idx1 = image_name_to_idx.get(database_image_names[image_id1]) |
| 563 |
idx2 = image_name_to_idx.get(database_image_names[image_id2]) |
| 564 |
if idx1 is None or idx2 is None: |
| 565 |
continue |
| 566 |
shared_points = max( |
| 567 |
overlap_counts[idx1, idx2], overlap_counts[idx2, idx1] |
| 568 |
) |
| 569 |
if shared_points < min_shared_points: |
| 570 |
database.delete_two_view_geometry(image_id1, image_id2) |
| 571 |
num_filtered += 1 |
| 572 |
logging.info( |
| 573 |
f"Depth covisibility filtering removed {num_filtered}/{len(pair_ids)} " |
| 574 |
"verified image pairs" |
| 575 |
) |
| 576 |
|
| 577 |
|
| 578 |
def run_spherical( |
| 579 |
input_image_path: Path, |
| 580 |
options: PanoramaReconstructionOptions, |
| 581 |
database_path: Path, |
| 582 |
rec_path: Path, |
| 583 |
) -> dict[int, pycolmap.Reconstruction]: |
| 584 |
"""Reconstruct directly on the equirectangular panoramas with the native |
| 585 |
EQUIRECTANGULAR camera model, without rendering perspective images.""" |
| 586 |
|
| 587 |
logging.info("Reconstructing with spherical camera") |
| 588 |
|
| 589 |
reader_options = pycolmap.ImageReaderOptions(camera_model="EQUIRECTANGULAR") |
| 590 |
extraction_options = pycolmap.FeatureExtractionOptions( |
| 591 |
use_gpu=options.use_gpu, |
| 592 |
gpu_index=options.gpu_index, |
| 593 |
num_threads=options.num_threads, |
| 594 |
) |
| 595 |
pycolmap.extract_features( |
| 596 |
database_path, |
| 597 |
input_image_path, |
| 598 |
reader_options=reader_options, |
| 599 |
camera_mode=pycolmap.CameraMode.SINGLE, |
| 600 |
extraction_options=extraction_options, |
| 601 |
) |
| 602 |
|
| 603 |
# A single EQUIRECTANGULAR camera observes the whole sphere from one |
| 604 |
# center, so there is no rig and no per-frame image-pair skipping. |
| 605 |
run_matcher(options, database_path, pycolmap.FeatureMatchingOptions()) |
| 606 |
if options.covisibility_path is not None: |
| 607 |
filter_database_by_covisibility( |
| 608 |
database_path, |
| 609 |
options.covisibility_path, |
| 610 |
options.covisibility_min_shared_points, |
| 611 |
) |
| 612 |
|
| 613 |
# The EQUIRECTANGULAR model has no focal length, principal point, or |
| 614 |
# distortion to refine; its (w, h) params are held constant in bundle |
| 615 |
# adjustment. |
| 616 |
if options.mapper == Mapper.INCREMENTAL: |
| 617 |
incremental_options = pycolmap.IncrementalPipelineOptions( |
| 618 |
num_threads=options.num_threads, random_seed=options.random_seed |
| 619 |
) |
| 620 |
recs = pycolmap.incremental_mapping( |
| 621 |
database_path, |
| 622 |
input_image_path, |
| 623 |
rec_path, |
| 624 |
incremental_options, |
| 625 |
) |
| 626 |
elif options.mapper == Mapper.GLOBAL: |
| 627 |
global_options = pycolmap.GlobalPipelineOptions( |
| 628 |
num_threads=options.num_threads, random_seed=options.random_seed |
| 629 |
) |
| 630 |
recs = pycolmap.global_mapping( |
| 631 |
database_path, input_image_path, rec_path, global_options |
| 632 |
) |
| 633 |
else: |
| 634 |
raise ValueError(f"Unknown mapper: {options.mapper}") |
| 635 |
for idx, rec in recs.items(): |
| 636 |
logging.info(f"#{idx} {rec.summary()}") |
| 637 |
return recs |
| 638 |
|
| 639 |
|
| 640 |
def run_perspective( |
| 641 |
input_image_path: Path, |
| 642 |
output_path: Path, |
| 643 |
options: PanoramaReconstructionOptions, |
| 644 |
database_path: Path, |
| 645 |
rec_path: Path, |
| 646 |
) -> dict[int, pycolmap.Reconstruction]: |
| 647 |
"""Render the panoramas into a rig of perspective virtual cameras and |
| 648 |
reconstruct from those.""" |
| 649 |
|
| 650 |
logging.info("Reconstructing with rig of perspective virtual cameras") |
| 651 |
|
| 652 |
image_dir = output_path / "images" |
| 653 |
mask_dir = output_path / "masks" |
| 654 |
image_dir.mkdir(exist_ok=True, parents=True) |
| 655 |
mask_dir.mkdir(exist_ok=True, parents=True) |
| 656 |
|
| 657 |
# Search for input images. |
| 658 |
pano_image_dir = input_image_path |
| 659 |
pano_image_names = sorted( |
| 660 |
p.relative_to(pano_image_dir).as_posix() |
| 661 |
for p in pano_image_dir.rglob("*") |
| 662 |
if not p.is_dir() |
| 663 |
) |
| 664 |
logging.info(f"Found {len(pano_image_names)} images in {pano_image_dir}.") |
| 665 |
|
| 666 |
processor = render_perspective_images( |
| 667 |
pano_image_names, |
| 668 |
pano_image_dir, |
| 669 |
image_dir, |
| 670 |
mask_dir, |
| 671 |
PANO_RENDER_OPTIONS[options.render_type], |
| 672 |
options.show_progress, |
| 673 |
) |
| 674 |
rig_config = processor.rig_config |
| 675 |
|
| 676 |
rendered_camera = rig_config.cameras[0].camera |
| 677 |
assert rendered_camera is not None # Make mypy happy. |
| 678 |
extraction_options = pycolmap.FeatureExtractionOptions( |
| 679 |
use_gpu=options.use_gpu, |
| 680 |
gpu_index=options.gpu_index, |
| 681 |
num_threads=options.num_threads, |
| 682 |
) |
| 683 |
pycolmap.extract_features( |
| 684 |
database_path, |
| 685 |
image_dir, |
| 686 |
reader_options=pycolmap.ImageReaderOptions( |
| 687 |
mask_path=mask_dir, |
| 688 |
camera_model=rendered_camera.model_name, |
| 689 |
camera_params=rendered_camera.params_to_string(), |
| 690 |
), |
| 691 |
camera_mode=pycolmap.CameraMode.PER_FOLDER, |
| 692 |
extraction_options=extraction_options, |
| 693 |
) |
| 694 |
|
| 695 |
with pycolmap.Database.open(database_path) as db: |
| 696 |
pycolmap.apply_rig_config([rig_config], db) |
| 697 |
|
| 698 |
matching_options = pycolmap.FeatureMatchingOptions() |
| 699 |
# We have perfect sensor_from_rig poses (except for potential stitching |
| 700 |
# artifacts by the spherical image provider), so we can perform geometric |
| 701 |
# verification using rig constraints. |
| 702 |
matching_options.rig_verification = True |
| 703 |
# The images within a frame do not have overlap due to the provided masks. |
| 704 |
matching_options.skip_image_pairs_in_same_frame = True |
| 705 |
run_matcher(options, database_path, matching_options) |
| 706 |
if options.covisibility_path is not None: |
| 707 |
filter_database_by_covisibility( |
| 708 |
database_path, |
| 709 |
options.covisibility_path, |
| 710 |
options.covisibility_min_shared_points, |
| 711 |
processor.split_image_name, |
| 712 |
) |
| 713 |
|
| 714 |
if options.mapper == Mapper.INCREMENTAL: |
| 715 |
opts = pycolmap.IncrementalPipelineOptions( |
| 716 |
num_threads=options.num_threads, |
| 717 |
random_seed=options.random_seed, |
| 718 |
ba_refine_sensor_from_rig=False, |
| 719 |
ba_refine_focal_length=False, |
| 720 |
ba_refine_principal_point=False, |
| 721 |
ba_refine_extra_params=False, |
| 722 |
) |
| 723 |
recs = pycolmap.incremental_mapping( |
| 724 |
database_path, image_dir, rec_path, opts |
| 725 |
) |
| 726 |
elif options.mapper == Mapper.GLOBAL: |
| 727 |
global_opts = pycolmap.GlobalPipelineOptions( |
| 728 |
num_threads=options.num_threads, |
| 729 |
random_seed=options.random_seed, |
| 730 |
mapper=pycolmap.GlobalMapperOptions( |
| 731 |
num_threads=options.num_threads, |
| 732 |
random_seed=options.random_seed, |
| 733 |
refine_sensor_from_rig=False, |
| 734 |
), |
| 735 |
) |
| 736 |
# Don't set these in the init to not overwrite custom default options. |
| 737 |
global_opts.mapper.bundle_adjustment.refine_focal_length = False |
| 738 |
global_opts.mapper.bundle_adjustment.refine_principal_point = False |
| 739 |
global_opts.mapper.bundle_adjustment.refine_extra_params = False |
| 740 |
recs = pycolmap.global_mapping( |
| 741 |
database_path, image_dir, rec_path, global_opts |
| 742 |
) |
| 743 |
else: |
| 744 |
raise ValueError(f"Unknown mapper: {options.mapper}") |
| 745 |
|
| 746 |
for idx, rec in recs.items(): |
| 747 |
logging.info(f"#{idx} {rec.summary()}") |
| 748 |
|
| 749 |
logging.info("Converting virtual cameras back to equirectangular") |
| 750 |
equirect_rec_path = output_path / "sparse_equirectangular" |
| 751 |
for idx, rec in recs.items(): |
| 752 |
equirect_rec = processor.convert_to_equirectangular(rec) |
| 753 |
model_path = equirect_rec_path / str(idx) |
| 754 |
model_path.mkdir(exist_ok=True, parents=True) |
| 755 |
equirect_rec.write(model_path) |
| 756 |
logging.info(f"#{idx} {equirect_rec.summary()}") |
| 757 |
return recs |
| 758 |
|
| 759 |
|
| 760 |
def reconstruct( |
| 761 |
input_image_path: Path, |
| 762 |
output_path: Path, |
| 763 |
options: PanoramaReconstructionOptions | None = None, |
| 764 |
) -> dict[int, pycolmap.Reconstruction]: |
| 765 |
"""Reconstruct 360-degree panoramas with spherical or virtual cameras.""" |
| 766 |
options = options or PanoramaReconstructionOptions() |
| 767 |
pycolmap.set_random_seed(options.random_seed) |
| 768 |
|
| 769 |
database_path = output_path / "database.db" |
| 770 |
if database_path.exists(): |
| 771 |
database_path.unlink() |
| 772 |
|
| 773 |
rec_path = output_path / "sparse" |
| 774 |
rec_path.mkdir(exist_ok=True, parents=True) |
| 775 |
|
| 776 |
if options.render_type == PanoRenderType.SPHERICAL: |
| 777 |
return run_spherical(input_image_path, options, database_path, rec_path) |
| 778 |
return run_perspective( |
| 779 |
input_image_path, |
| 780 |
output_path, |
| 781 |
options, |
| 782 |
database_path, |
| 783 |
rec_path, |
| 784 |
) |