Debian Codegraph @

benchmark/reconstruction/evaluation/tartanair/depth_covisibility.py

raw
1 """Depth-based covisibility for TartanAir equirectangular images."""
2
3 from pathlib import Path
4
5 import numpy as np
6 import numpy.typing as npt
7
8 SAMPLE_STRIDE = 4
9 MAX_DEPTH = 256.0
10 ABSOLUTE_TOLERANCE = 0.25
11 RELATIVE_TOLERANCE = 0.01
12
13
14 def equirectangular_rays(
15 width: int, height: int, stride: int
16 ) -> npt.NDArray[np.float64]:
17 x = np.arange(0, width, stride, dtype=np.float64) + 0.5
18 y = np.arange(0, height, stride, dtype=np.float64) + 0.5
19 u: npt.NDArray[np.float64]
20 v: npt.NDArray[np.float64]
21 u, v = np.meshgrid(x / width, y / height)
22 yaw = (2.0 * u - 1.0) * np.pi
23 pitch = (1.0 - 2.0 * v) * np.pi / 2.0
24 cos_pitch = np.cos(pitch)
25 return np.column_stack(
26 [
27 np.sin(yaw).ravel() * cos_pitch.ravel(),
28 -np.sin(pitch).ravel(),
29 np.cos(yaw).ravel() * cos_pitch.ravel(),
30 ]
31 )
32
33
34 def _project_equirectangular(
35 points_in_camera: npt.NDArray[np.float64], width: int, height: int
36 ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]:
37 yaw = np.arctan2(points_in_camera[:, 0], points_in_camera[:, 2])
38 pitch = -np.arctan2(
39 points_in_camera[:, 1],
40 np.linalg.norm(points_in_camera[:, [0, 2]], axis=1),
41 )
42 x = np.floor((1.0 + yaw / np.pi) * width / 2.0).astype(np.int64)
43 y = np.floor((1.0 - pitch * 2.0 / np.pi) * height / 2.0).astype(np.int64)
44 return np.mod(x, width), np.clip(y, 0, height - 1)
45
46
47 def compute_covisibility_counts(
48 depths: npt.NDArray[np.uint16],
49 world_from_cameras: npt.NDArray[np.float64],
50 depth_scale: float,
51 *,
52 stride: int = SAMPLE_STRIDE,
53 max_depth: float = MAX_DEPTH,
54 absolute_tolerance: float = ABSOLUTE_TOLERANCE,
55 relative_tolerance: float = RELATIVE_TOLERANCE,
56 ) -> npt.NDArray[np.uint32]:
57 if depths.ndim != 3:
58 raise ValueError(f"Expected depth array (N,H,W), got {depths.shape}")
59 if world_from_cameras.shape != (len(depths), 4, 4):
60 raise ValueError(
61 "Expected one 4x4 world_from_camera matrix per depth image"
62 )
63 if depth_scale <= 0:
64 raise ValueError("depth_scale must be positive")
65
66 _, height, width = depths.shape
67 rays = equirectangular_rays(width, height, stride)
68 sampled_depths = (
69 depths[:, ::stride, ::stride]
70 .reshape(len(depths), -1)
71 .astype(np.float64)
72 / depth_scale
73 )
74 counts: npt.NDArray[np.uint32] = np.zeros(
75 (len(depths), len(depths)), dtype=np.uint32
76 )
77
78 for source_idx in range(len(depths)):
79 source_depth = sampled_depths[source_idx]
80 valid = (source_depth > 0) & (source_depth <= max_depth)
81 if not np.any(valid):
82 continue
83 source_points = rays[valid] * source_depth[valid, np.newaxis]
84 source_pose = world_from_cameras[source_idx]
85 points_in_world = (
86 source_pose[:3, :3] @ source_points.T
87 + source_pose[:3, 3, np.newaxis]
88 ).T
89 for target_idx in range(len(depths)):
90 if source_idx == target_idx:
91 counts[source_idx, target_idx] = np.count_nonzero(valid)
92 continue
93 target_pose = world_from_cameras[target_idx]
94 points_in_target = (
95 target_pose[:3, :3].T @ (points_in_world - target_pose[:3, 3]).T
96 ).T
97 projected_depth = np.linalg.norm(points_in_target, axis=1)
98 x, y = _project_equirectangular(points_in_target, width, height)
99 target_depth = depths[target_idx, y, x].astype(np.float64)
100 target_depth /= depth_scale
101 tolerance = np.maximum(
102 absolute_tolerance, relative_tolerance * projected_depth
103 )
104 visible = (
105 (target_depth > 0)
106 & (target_depth <= max_depth)
107 & (np.abs(target_depth - projected_depth) <= tolerance)
108 )
109 counts[source_idx, target_idx] = np.count_nonzero(visible)
110 return counts
111
112
113 def covisibility_is_current(path: Path, image_names: list[str]) -> bool:
114 if not path.exists():
115 return False
116 try:
117 with np.load(path) as covisibility:
118 return (
119 covisibility["image_names"].tolist() == image_names
120 and covisibility["sample_stride"].item() == SAMPLE_STRIDE
121 and covisibility["max_depth"].item() == MAX_DEPTH
122 and covisibility["absolute_tolerance"].item()
123 == ABSOLUTE_TOLERANCE
124 and covisibility["relative_tolerance"].item()
125 == RELATIVE_TOLERANCE
126 )
127 except (KeyError, OSError, ValueError):
128 return False
129
130
131 def write_covisibility(
132 output_path: Path,
133 depth_paths: list[Path],
134 image_names: list[str],
135 world_from_cameras: npt.NDArray[np.float64],
136 depth_scale: float,
137 ) -> None:
138 from PIL import Image
139
140 depths = np.stack(
141 [np.asarray(Image.open(path), dtype=np.uint16) for path in depth_paths]
142 )
143 counts = compute_covisibility_counts(
144 depths, world_from_cameras, depth_scale
145 )
146 np.savez_compressed(
147 output_path,
148 image_names=np.asarray(image_names),
149 directed_overlap_counts=counts,
150 sample_stride=SAMPLE_STRIDE,
151 max_depth=MAX_DEPTH,
152 absolute_tolerance=ABSOLUTE_TOLERANCE,
153 relative_tolerance=RELATIVE_TOLERANCE,
154 )