Debian Codegraph @

benchmark/reconstruction/evaluation/imc.py

raw
1 # Copyright (c), ETH Zurich and UNC Chapel Hill.
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
6 #
7 # * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 #
10 # * Redistributions in binary form must reproduce the above copyright
11 # notice, this list of conditions and the following disclaimer in the
12 # documentation and/or other materials provided with the distribution.
13 #
14 # * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
15 # its contributors may be used to endorse or promote products derived
16 # from this software without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
22 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29
30 import csv
31 import tempfile
32 from collections import defaultdict
33 from pathlib import Path
34
35 import numpy as np
36 from PIL import Image as PilImage
37
38 import pycolmap
39
40 from .utils import Dataset, SceneInfo
41
42 _POINTS3D_FILENAME = "points3D.txt"
43 _TRAIN_LABELS_FILENAME = "train_labels.csv"
44 # Scene label used by IMC2025 to mark images that do not belong to any scene.
45 _OUTLIER_SCENE = "outliers"
46 # Fallback image dimensions if an image file cannot be opened. Only used to
47 # build placeholder GT cameras, which do not affect relative pose evaluation.
48 _DEFAULT_IMAGE_WIDTH = 1024
49 _DEFAULT_IMAGE_HEIGHT = 768
50
51
52 def _read_points3D_lenient(
53 path: Path, valid_image_ids: set[int]
54 ) -> dict[int, pycolmap.Point3D]:
55 """Parse points3D.txt, dropping track elements whose image_id is not in
56 valid_image_ids and skipping any point3D whose track becomes empty."""
57 points3D: dict[int, pycolmap.Point3D] = {}
58 with open(path) as f:
59 for line in f:
60 line = line.strip()
61 if not line or line.startswith("#"):
62 continue
63 tokens = line.split()
64 point3D_id = int(tokens[0])
65 xyz = [float(v) for v in tokens[1:4]]
66 rgb = [int(v) for v in tokens[4:7]]
67 error = float(tokens[7])
68 elements = []
69 track_tokens = tokens[8:]
70 for i in range(0, len(track_tokens), 2):
71 image_id = int(track_tokens[i])
72 point2D_idx = int(track_tokens[i + 1])
73 if image_id in valid_image_ids:
74 elements.append(
75 pycolmap.TrackElement(image_id, point2D_idx)
76 )
77 if not elements:
78 continue
79 point3D = pycolmap.Point3D()
80 point3D.xyz = np.array(xyz)
81 point3D.color = np.array(rgb, dtype=np.uint8)
82 point3D.error = error
83 point3D.track = pycolmap.Track(elements)
84 points3D[point3D_id] = point3D
85 return points3D
86
87
88 def _read_sparse_sfm_without_points3D(
89 sfm_path: Path,
90 ) -> pycolmap.Reconstruction:
91 """Read an SfM reconstruction's cameras/rigs/frames/images, skipping
92 points3D entirely.
93
94 Some IMC scenes ship with points3D.txt referencing image_ids absent from
95 images.txt, which makes the strict pycolmap reader abort. Callers can
96 parse points3D separately via _read_points3D_lenient if needed.
97 """
98 with tempfile.TemporaryDirectory() as tmp:
99 tmp_path = Path(tmp)
100 for src_file in sfm_path.iterdir():
101 if src_file.name == _POINTS3D_FILENAME:
102 continue
103 (tmp_path / src_file.name).symlink_to(src_file.resolve())
104 (tmp_path / _POINTS3D_FILENAME).touch()
105 return pycolmap.Reconstruction(tmp_path)
106
107
108 class _DatasetIMC(Dataset):
109 @property
110 def position_accuracy_gt(self):
111 return 0.02
112
113 @property
114 def supports_covisibility_filtering(self) -> bool:
115 # IMC2023/2024 ship per-scene COLMAP reconstructions with real
116 # intrinsics and 3D points, so covisibility filtering is supported.
117 return True
118
119 def _has_ground_truth(self, scene_path: Path) -> bool:
120 """Whether ground truth is available for a scene.
121
122 The default IMC layout ships a per-scene COLMAP reconstruction under
123 sfm/; scenes without it are skipped.
124 """
125 return (scene_path / "sfm").exists()
126
127 def _image_path(self, scene_path: Path) -> Path:
128 """Folder holding a scene's images (a dedicated images/ subfolder)."""
129 return scene_path / "images"
130
131 def _count_images(self, scene: str, image_path: Path) -> int:
132 """Number of images for a scene (image files present on disk)."""
133 return sum(
134 1
135 for p in image_path.iterdir()
136 if p.is_file() and p.suffix.lower() in {".jpg", ".jpeg", ".png"}
137 )
138
139 def list_scenes(self):
140 folder_name = f"imc{self.year}"
141
142 scene_infos = []
143 for category_path in Path(
144 self.data_path / f"{folder_name}/train"
145 ).iterdir():
146 if not category_path.is_dir() or (
147 self.categories and category_path.name not in self.categories
148 ):
149 continue
150
151 category = category_path.name
152
153 for scene_path in category_path.iterdir():
154 if not scene_path.is_dir():
155 continue
156
157 scene = scene_path.name
158 if self.scenes and scene not in self.scenes:
159 continue
160
161 if not self._has_ground_truth(scene_path):
162 pycolmap.logging.warning(
163 f"Skipping dataset=IMC{self.year}, "
164 f"category={category}, scene={scene}, "
165 "because the GT reconstruction is missing"
166 )
167 continue
168
169 image_path = self._image_path(scene_path)
170 sparse_gt_path = scene_path / "sparse_gt"
171 workspace_path = (
172 self.run_path
173 / self.run_name
174 / folder_name
175 / category
176 / scene
177 )
178
179 scene_info = SceneInfo(
180 dataset=f"IMC{self.year}",
181 category=category,
182 scene=scene,
183 num_images=self._count_images(scene, image_path),
184 workspace_path=workspace_path,
185 image_path=image_path,
186 sparse_gt_path=sparse_gt_path,
187 has_camera_priors=False,
188 colmap_extra_args=None,
189 )
190
191 scene_infos.append(scene_info)
192
193 return scene_infos
194
195 def prepare_scene(self, scene_info):
196 if scene_info.sparse_gt_path.exists():
197 return
198
199 scene_path = scene_info.image_path.parent
200 sfm_path = scene_path / "sfm"
201
202 sparse_sfm = _read_sparse_sfm_without_points3D(sfm_path)
203 sparse_gt = pycolmap.Reconstruction()
204
205 train_image_ids = set()
206 train_image_names = set(
207 image.name for image in scene_info.image_path.iterdir()
208 )
209 for image in sparse_sfm.images.values():
210 if image.name in train_image_names:
211 train_image_ids.add(image.image_id)
212 for camera in sparse_sfm.cameras.values():
213 sparse_gt.add_camera(camera)
214 for rig in sparse_sfm.rigs.values():
215 sparse_gt.add_rig(rig)
216 for frame in sparse_sfm.frames.values():
217 has_train_image = False
218 for data_id in frame.image_ids:
219 if data_id.id in train_image_ids:
220 has_train_image = True
221 break
222 if has_train_image:
223 frame.reset_rig_ptr()
224 sparse_gt.add_frame(frame)
225 for image in sparse_sfm.images.values():
226 if image.image_id not in train_image_ids:
227 continue
228 if image.camera_id not in sparse_gt.cameras:
229 sparse_gt.add_camera(image.camera)
230 image.reset_camera_ptr()
231 image.reset_frame_ptr()
232 sparse_gt.add_image(image)
233
234 points3D = _read_points3D_lenient(
235 sfm_path / _POINTS3D_FILENAME, train_image_ids
236 )
237 for point3D_id, point3D in points3D.items():
238 sparse_gt.add_point3D_with_id(point3D_id, point3D)
239
240 scene_info.sparse_gt_path.mkdir(exist_ok=True)
241 sparse_gt.write(scene_info.sparse_gt_path)
242
243
244 class DatasetIMC2023(_DatasetIMC):
245 def __init__(
246 self,
247 data_path: Path,
248 categories: list[str],
249 scenes: list[Path],
250 run_path: Path,
251 run_name: str,
252 ):
253 super().__init__(
254 data_path=data_path,
255 categories=categories,
256 scenes=scenes,
257 run_path=run_path,
258 run_name=run_name,
259 )
260 self.year = 2023
261
262
263 class DatasetIMC2024(_DatasetIMC):
264 def __init__(
265 self,
266 data_path: Path,
267 categories: list[str],
268 scenes: list[Path],
269 run_path: Path,
270 run_name: str,
271 ):
272 super().__init__(
273 data_path=data_path,
274 categories=categories,
275 scenes=scenes,
276 run_path=run_path,
277 run_name=run_name,
278 )
279 self.year = 2024
280
281
282 class DatasetIMC2025(_DatasetIMC):
283 """IMC2025 benchmark dataset.
284
285 Unlike IMC2023/IMC2024, the ground truth is provided as poses in a single
286 train_labels.csv rather than per-scene COLMAP reconstructions, and each
287 IMC "dataset" folder mixes images from multiple scenes plus outliers that
288 belong to no scene.
289
290 Here each IMC dataset is a single benchmark scene: all of its images (every
291 scene plus outliers) are fed into one reconstruction problem, which
292 typically yields several sub-models. Evaluation uses the base-class
293 set-based, GT-component-aware pose metric (relative by default; absolute is
294 also supported), driven by a per-GT-scene grouping supplied via
295 scene_info.image_name_to_component, which jointly penalizes wrong merges,
296 registered outliers, and failed/fragmented registrations.
297
298 Ground-truth 3D points and intrinsics are unavailable, so the GT
299 reconstruction (used only for stats and covisibility heuristics) uses
300 placeholder pinhole cameras built from the actual image dimensions. All
301 scenes are stored in one GT reconstruction, each with its own gauge; the
302 metric only ever compares poses within the same scene, so the (arbitrary)
303 relative placement of different scenes does not matter.
304
305 IMC2025 has no coarse category grouping: the downloaded layout places every
306 dataset under train/all/<dataset>, so the base iteration reports "all" as
307 the (single) category and each dataset as its own scene.
308 """
309
310 def __init__(
311 self,
312 data_path: Path,
313 categories: list[str],
314 scenes: list[Path],
315 run_path: Path,
316 run_name: str,
317 ):
318 super().__init__(
319 data_path=data_path,
320 categories=categories,
321 scenes=scenes,
322 run_path=run_path,
323 run_name=run_name,
324 )
325 self.year = 2025
326 # Lazily-parsed {dataset: [image, ...]} from train_labels.csv.
327 self._images_by_dataset_cache: dict[str, list[str]] | None = None
328
329 @staticmethod
330 def _parse_floats(text: str) -> list[float] | None:
331 """Parse a list of floats from an IMC label field.
332
333 IMC stores matrices/vectors as ';'-separated values inside a single CSV
334 field (falls back to whitespace separation). Returns None if the field
335 is empty or cannot be fully parsed as floats.
336 """
337 if text is None:
338 return None
339 text = text.strip()
340 if not text:
341 return None
342 tokens = text.split(";") if ";" in text else text.split()
343 try:
344 return [float(t) for t in tokens if t.strip() != ""]
345 except ValueError:
346 return None
347
348 @staticmethod
349 def _read_imc2025_labels(
350 path: Path,
351 ) -> tuple[dict[tuple[str, str], list[dict]], dict[str, list[str]]]:
352 """Parse IMC2025 train_labels.csv.
353
354 Expected columns: dataset, scene, image, rotation_matrix (row-major
355 3x3, cam_from_world), translation_vector (cam_from_world).
356
357 Returns a tuple of:
358 - gt_rows_by_scene: {(dataset, scene): [{image, R, t}, ...]} for all
359 non-outlier images with a parseable pose (the ground truth).
360 - images_by_dataset: {dataset: [image, ...]} for every image,
361 including outliers (the full input to the reconstruction problem).
362 """
363 gt_rows_by_scene: dict[tuple[str, str], list[dict]] = defaultdict(list)
364 images_by_dataset: dict[str, list[str]] = defaultdict(list)
365 with open(path, newline="") as f:
366 reader = csv.DictReader(f)
367 for row in reader:
368 dataset = (row.get("dataset") or "").strip()
369 scene = (row.get("scene") or "").strip()
370 image = (row.get("image") or "").strip()
371 if not dataset or not image:
372 continue
373 images_by_dataset[dataset].append(image)
374 if not scene or scene == _OUTLIER_SCENE:
375 continue
376 rotation = DatasetIMC2025._parse_floats(
377 row.get("rotation_matrix", "")
378 )
379 translation = DatasetIMC2025._parse_floats(
380 row.get("translation_vector", "")
381 )
382 if (
383 rotation is None
384 or translation is None
385 or len(rotation) != 9
386 or len(translation) != 3
387 ):
388 continue
389 gt_rows_by_scene[(dataset, scene)].append(
390 {
391 "image": image,
392 "R": np.array(rotation, dtype=np.float64).reshape(3, 3),
393 "t": np.array(translation, dtype=np.float64),
394 }
395 )
396 return gt_rows_by_scene, images_by_dataset
397
398 @staticmethod
399 def _build_imc2025_gt_reconstruction(
400 rows: list[dict], image_dir: Path
401 ) -> pycolmap.Reconstruction:
402 """Build a placeholder GT reconstruction from IMC2025 label rows.
403
404 Each row provides {image, R, t} with cam_from_world extrinsics. IMC2025
405 ships neither intrinsics nor 3D points, so we attach a rough pinhole
406 camera sized from each image (falling back to default dimensions if the
407 file cannot be opened) and add no points3D. The result has one
408 rig/frame/camera/image per row and is only used for pose-based
409 evaluation and covisibility heuristics, not for anything that depends
410 on intrinsics.
411 """
412 reconstruction = pycolmap.Reconstruction()
413 for idx, row in enumerate(rows, start=1):
414 image_name = row["image"]
415 image_file = image_dir / image_name
416 try:
417 width, height = PilImage.open(image_file).size
418 except (OSError, ValueError):
419 pycolmap.logging.warning(
420 f"Could not read dimensions for {image_file}, "
421 "using placeholder camera size"
422 )
423 width = _DEFAULT_IMAGE_WIDTH
424 height = _DEFAULT_IMAGE_HEIGHT
425
426 # Intrinsics are not provided by IMC; use a rough pinhole guess.
427 # This only affects covisibility/alignment heuristics, not the
428 # relative pose error, which depends solely on poses.
429 focal = 1.2 * max(width, height)
430 camera = pycolmap.Camera(
431 camera_id=idx,
432 model=pycolmap.CameraModelId.PINHOLE,
433 width=width,
434 height=height,
435 params=[focal, focal, width / 2.0, height / 2.0],
436 )
437 reconstruction.add_camera_with_trivial_rig(camera)
438 image = pycolmap.Image(
439 image_id=idx,
440 camera_id=idx,
441 name=image_name,
442 )
443 # IMC stores cam_from_world (x_cam = R * x_world + t). With a
444 # trivial rig, sensor_from_rig is identity, so cam_from_world
445 # equals rig_from_world.
446 cam_from_world = pycolmap.Rigid3d(
447 np.hstack([row["R"], row["t"].reshape(3, 1)])
448 )
449 reconstruction.add_image_with_trivial_frame(image, cam_from_world)
450 return reconstruction
451
452 @property
453 def supports_covisibility_filtering(self) -> bool:
454 # IMC2025 ships neither intrinsics nor 3D points, and the placeholder GT
455 # stores every scene in its own arbitrary gauge. Feeding that to the
456 # frustum filter would delete valid verified pairs based on guessed
457 # focal/depth values, so covisibility filtering is disabled here.
458 return False
459
460 def _labels_path(self) -> Path:
461 """Path to train_labels.csv (sibling of the train/ folder)."""
462 return self.data_path / "imc2025" / _TRAIN_LABELS_FILENAME
463
464 def _images_by_dataset(self) -> dict[str, list[str]]:
465 """Parse (and cache) the {dataset: [image, ...]} map from the labels."""
466 if self._images_by_dataset_cache is None:
467 _, self._images_by_dataset_cache = self._read_imc2025_labels(
468 self._labels_path()
469 )
470 return self._images_by_dataset_cache
471
472 def _has_ground_truth(self, scene_path: Path) -> bool:
473 """IMC2025 ships GT as poses in train_labels.csv rather than a
474 per-scene sfm/ reconstruction, so availability is determined by the
475 existence of the labels file."""
476 return self._labels_path().exists()
477
478 def _image_path(self, scene_path: Path) -> Path:
479 # All of a dataset's images live directly in the dataset folder.
480 return scene_path
481
482 def _count_images(self, scene: str, image_path: Path) -> int:
483 # The folder contains exactly the labeled images; count them from the
484 # labels and warn about any listed image missing on disk.
485 num_images = 0
486 num_missing = 0
487 for name in self._images_by_dataset().get(scene, []):
488 if (image_path / name).exists():
489 num_images += 1
490 else:
491 num_missing += 1
492 if num_missing:
493 pycolmap.logging.warning(
494 f"IMC2025 dataset={scene}: {num_missing} listed "
495 "image(s) not found on disk"
496 )
497 return num_images
498
499 def prepare_scene(self, scene_info):
500 gt_rows_by_scene, _ = self._read_imc2025_labels(self._labels_path())
501 dataset = scene_info.scene
502
503 # Each GT scene within this IMC dataset is its own reconstruction; map
504 # every GT image name to a distinct integer id so the base-class
505 # set-based metric only ever compares poses within the same scene.
506 # Outliers are already excluded from gt_rows_by_scene, so they are
507 # absent from the mapping and penalized when registered.
508 scene_to_component: dict[str, int] = {}
509 image_name_to_component: dict[str, int] = {}
510 rows = []
511 for (ds, scene), scene_rows in sorted(gt_rows_by_scene.items()):
512 if ds != dataset:
513 continue
514 component = scene_to_component.setdefault(
515 scene, len(scene_to_component)
516 )
517 for row in scene_rows:
518 image_name_to_component[row["image"]] = component
519 rows.extend(scene_rows)
520 scene_info.image_name_to_component = image_name_to_component
521
522 if scene_info.sparse_gt_path.exists():
523 return
524
525 sparse_gt = self._build_imc2025_gt_reconstruction(
526 rows, scene_info.image_path
527 )
528
529 scene_info.sparse_gt_path.mkdir(parents=True, exist_ok=True)
530 sparse_gt.write(scene_info.sparse_gt_path)