Debian Codegraph @

benchmark/reconstruction/evaluation/covisibility.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 dataclasses
31 import functools
32 from pathlib import Path
33
34 import numpy as np
35 import numpy.typing as npt
36
37 import pycolmap
38
39 from .geometry import vec_angular_dist_deg
40
41
42 @dataclasses.dataclass
43 class Frustum:
44 # Sampled 3D points on the frustum in world coordinates.
45 points: npt.NDArray[np.floating]
46 # Near/far depth bounds (in camera coordinates) for the frustum.
47 depth_range: tuple[float, float]
48
49
50 def _estimate_depth_ranges(
51 sparse_gt: pycolmap.Reconstruction,
52 percentile_near: float = 2.0,
53 percentile_far: float = 98.0,
54 min_num_points: int = 10,
55 ) -> dict[int, tuple[float, float]]:
56 """Estimate per-image near/far depth range from GT 3D points.
57
58 For each image, computes depths of the 3D points visible in that image
59 and returns percentile-based near/far bounds. Falls back to (0.1, 100.0)
60 for images with insufficient depth data.
61 """
62 default_range = (0.1, 100.0)
63 depth_ranges: dict[int, tuple[float, float]] = {}
64
65 for image_id, image in sparse_gt.images.items():
66 valid = [
67 p.point3D_id
68 for p in image.points2D
69 if p.point3D_id != pycolmap.INVALID_POINT3D_ID
70 ]
71 if len(valid) < min_num_points:
72 depth_ranges[image_id] = default_range
73 continue
74
75 points_xyz = np.array([sparse_gt.points3D[pid].xyz for pid in valid])
76 cam_from_world = image.cam_from_world()
77 points_in_cam = (
78 cam_from_world.rotation.matrix() @ points_xyz.T
79 + cam_from_world.translation[:, np.newaxis]
80 )
81 depths = points_in_cam[2, :]
82 pos_depths = depths[depths > 0]
83
84 if len(pos_depths) < min_num_points:
85 depth_ranges[image_id] = default_range
86 continue
87
88 near, far = np.percentile(pos_depths, [percentile_near, percentile_far])
89 depth_ranges[image_id] = (float(near), float(far))
90
91 return depth_ranges
92
93
94 def _sample_frustum_points(
95 image: pycolmap.Image,
96 camera: pycolmap.Camera,
97 near: float,
98 far: float,
99 num_steps: int = 5,
100 ) -> npt.NDArray[np.floating]:
101 """Sample points on a camera viewing frustum in world coordinates.
102
103 Samples a grid of points on the image plane (corners, edges, and interior)
104 at multiple depths between near and far, then transforms them to world
105 space for more accurate overlap checks.
106 """
107 w, h = camera.width, camera.height
108 us = np.linspace(0, w, num_steps)
109 vs = np.linspace(0, h, num_steps)
110 grid_x, grid_y = np.meshgrid(us, vs)
111 pixels = np.stack([grid_x.ravel(), grid_y.ravel()], axis=1)
112 cam_points = camera.cam_from_img(pixels)
113 assert cam_points is not None
114 cam_rays = np.column_stack([cam_points, np.ones(len(cam_points))])
115
116 depths = np.linspace(near, far, num_steps)
117 points_in_cam = np.vstack([cam_rays * d for d in depths])
118
119 world_from_cam = image.cam_from_world().inverse()
120 points_in_world = (
121 world_from_cam.rotation.matrix() @ points_in_cam.T
122 + world_from_cam.translation[:, np.newaxis]
123 ).T
124 return points_in_world
125
126
127 def _build_image_point3D_sets(
128 sparse_gt: pycolmap.Reconstruction,
129 ) -> dict[int, set[int]]:
130 """Build a mapping from image ID to the set of observed 3D point IDs."""
131 image_points: dict[int, set[int]] = {}
132 for image_id, image in sparse_gt.images.items():
133 image_points[image_id] = {
134 p.point3D_id
135 for p in image.points2D
136 if p.point3D_id != pycolmap.INVALID_POINT3D_ID
137 }
138 return image_points
139
140
141 def _compute_frustums_for_all_images(
142 sparse_gt: pycolmap.Reconstruction,
143 frustum_near: float | None,
144 frustum_far: float | None,
145 ) -> dict[int, Frustum]:
146 depth_ranges: dict[int, tuple[float, float]] = {}
147 if frustum_near is None or frustum_far is None:
148 depth_ranges = _estimate_depth_ranges(sparse_gt)
149
150 frustums: dict[int, Frustum] = {}
151 for image_id, image_gt in sparse_gt.images.items():
152 camera_gt = sparse_gt.cameras[image_gt.camera_id]
153 est_near, est_far = depth_ranges.get(image_id, (0.1, 100.0))
154 near = frustum_near if frustum_near is not None else est_near
155 far = frustum_far if frustum_far is not None else est_far
156 frustums[image_id] = Frustum(
157 points=_sample_frustum_points(image_gt, camera_gt, near, far),
158 depth_range=(near, far),
159 )
160 return frustums
161
162
163 def _is_pair_covisible_by_tracks(
164 image1: pycolmap.Image,
165 image2: pycolmap.Image,
166 image_point3D_sets: dict[int, set[int]],
167 min_shared_points: int,
168 ) -> bool:
169 shared = len(
170 image_point3D_sets[image1.image_id]
171 & image_point3D_sets[image2.image_id]
172 )
173 return shared >= min_shared_points
174
175
176 def _is_pair_covisible_by_frustum(
177 image1: pycolmap.Image,
178 image2: pycolmap.Image,
179 sparse_gt: pycolmap.Reconstruction,
180 frustums: dict[int, Frustum],
181 max_viewing_angle_deg: float,
182 ) -> bool:
183 """Check whether two cameras have overlapping viewing frustums.
184
185 Uses a three-stage test that short-circuits on the first definitive result:
186 1. Viewing angle: reject if angle between viewing directions exceeds the
187 threshold.
188 2. Vertex projection: accept if any of A's frustum vertices projects into
189 B's image (or vice versa) with positive depth within the target
190 image's expected GT depth range.
191 """
192 if (
193 vec_angular_dist_deg(
194 image1.viewing_direction(), image2.viewing_direction()
195 )
196 > max_viewing_angle_deg
197 ):
198 return False
199
200 camera1 = sparse_gt.cameras[image1.camera_id]
201 camera2 = sparse_gt.cameras[image2.camera_id]
202
203 def project_and_check(
204 frustum: Frustum,
205 image: pycolmap.Image,
206 camera: pycolmap.Camera,
207 ) -> bool:
208 near, far = frustums[image.image_id].depth_range
209 cam_from_world = image.cam_from_world()
210 R = cam_from_world.rotation.matrix()
211 t = cam_from_world.translation
212 points_in_cam = (R @ frustum.points.T + t[:, np.newaxis]).T
213 depths = points_in_cam[:, 2]
214 mask = (depths >= near) & (depths <= far)
215 if not np.any(mask):
216 return False
217 img_points = camera.img_from_cam(points_in_cam[mask])
218 if img_points is None:
219 return False
220 in_bounds = (
221 (img_points[:, 0] >= 0)
222 & (img_points[:, 0] <= camera.width)
223 & (img_points[:, 1] >= 0)
224 & (img_points[:, 1] <= camera.height)
225 )
226 return bool(np.any(in_bounds))
227
228 return project_and_check(
229 frustums[image1.image_id], image2, camera2
230 ) or project_and_check(frustums[image2.image_id], image1, camera1)
231
232
233 def filter_covisibility(
234 database_path: Path,
235 sparse_gt: pycolmap.Reconstruction,
236 covisibility_frustum_near: float | None,
237 covisibility_frustum_far: float | None,
238 max_viewing_angle_deg: float,
239 min_shared_points: int = 0,
240 ) -> None:
241 """Filter non-covisible image pairs from the database.
242
243 If the GT reconstruction contains 3D point tracks and min_shared_points > 0,
244 uses track-based covisibility: two images are covisible if they share at
245 least min_shared_points common 3D points. Otherwise, falls back to
246 frustum-based overlap checking using GT camera poses and intrinsics.
247 """
248 pycolmap.logging.info("Filtering non-covisible image pairs")
249
250 use_tracks = min_shared_points > 0 and sparse_gt.num_points3D() > 0
251
252 if use_tracks:
253 pycolmap.logging.info(
254 f"Using track-based covisibility "
255 f"(min_shared_points={min_shared_points})"
256 )
257 image_point3D_sets = _build_image_point3D_sets(sparse_gt)
258 is_covisible = functools.partial(
259 _is_pair_covisible_by_tracks,
260 image_point3D_sets=image_point3D_sets,
261 min_shared_points=min_shared_points,
262 )
263 else:
264 if min_shared_points > 0:
265 pycolmap.logging.warning(
266 "No GT 3D points available for track-based covisibility, "
267 "falling back to frustum-based check"
268 )
269 frustums = _compute_frustums_for_all_images(
270 sparse_gt, covisibility_frustum_near, covisibility_frustum_far
271 )
272 is_covisible = functools.partial(
273 _is_pair_covisible_by_frustum,
274 sparse_gt=sparse_gt,
275 frustums=frustums,
276 max_viewing_angle_deg=max_viewing_angle_deg,
277 )
278
279 images_gt_by_name: dict[str, pycolmap.Image] = {
280 image_gt.name: image_gt for image_gt in sparse_gt.images.values()
281 }
282
283 with pycolmap.Database.open(str(database_path)) as database:
284 db_id_to_name: dict[int, str] = {
285 db_image.image_id: db_image.name
286 for db_image in database.read_all_images()
287 }
288
289 pair_ids, _ = database.read_two_view_geometry_num_inliers()
290 total_pairs = len(pair_ids)
291 filtered_count = 0
292 missing_gt_image_names: set[str] = set()
293
294 for pair_id in pair_ids:
295 image_id1, image_id2 = pycolmap.pair_id_to_image_pair(pair_id)
296 name1 = db_id_to_name.get(image_id1)
297 name2 = db_id_to_name.get(image_id2)
298
299 if name1 is None or name2 is None:
300 continue
301
302 image_gt1 = images_gt_by_name.get(name1)
303 image_gt2 = images_gt_by_name.get(name2)
304 if image_gt1 is None:
305 missing_gt_image_names.add(name1)
306 if image_gt2 is None:
307 missing_gt_image_names.add(name2)
308 if image_gt1 is None or image_gt2 is None:
309 continue
310
311 if not is_covisible(image_gt1, image_gt2):
312 # Only delete the two-view geometry, so it will be ignored
313 # during reconstruction but keep the raw matches, so upon
314 # re-running the pipeline, the matches will be re-computed,
315 # if not filtering by covisibility.
316 database.delete_two_view_geometry(image_id1, image_id2)
317 filtered_count += 1
318
319 pycolmap.logging.info(
320 f"Co-visibility filtering: {filtered_count}/{total_pairs} pairs "
321 f"removed, {total_pairs - filtered_count} kept"
322 )
323 if missing_gt_image_names:
324 pycolmap.logging.warning(
325 f"Skipped pairs involving {len(missing_gt_image_names)} "
326 f"database image(s) without a GT counterpart"
327 )