StarAtNyte1 commited on
Commit
0126f3c
·
verified ·
1 Parent(s): fc39f3f

Upload s23dr_2026/inference.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. s23dr_2026/inference.py +262 -0
s23dr_2026/inference.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import numpy as np
4
+ import torch
5
+ from hoho2025.color_mappings import gestalt_color_mapping
6
+
7
+ from .dataset import sample_points, colors_to_features, combined_sampling, compute_norm_params
8
+ from .model import WireframeBase
9
+ from .scene import Scene
10
+ from .postprocess import (
11
+ add_edges_by_translated_edge_symmetry,
12
+ add_gap_fill_edges_from_candidates,
13
+ filter_edges_by_length,
14
+ merge_vertices_with_features,
15
+ post_process_wireframe,
16
+ project_near_horizontal_edges_to_xz_plane,
17
+ remove_solitary_edges as remove_solitary_edges_from_wireframe,
18
+ snap_edges_to_principal_xz_directions,
19
+ )
20
+
21
+
22
+ def _rotation_matrix_y(theta: float) -> np.ndarray:
23
+ c, s = np.cos(theta), np.sin(theta)
24
+ return np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]], dtype=np.float32)
25
+
26
+
27
+ def get_colmap_points(scene: Scene) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
28
+ assert len(scene.data["ade"]) == len(scene.data["gestalt"]) == scene.num_images
29
+ ade = [scene.ade(idx) for idx in range(scene.num_images)]
30
+ gestalt = [scene.gestalt(idx) for idx in range(scene.num_images)]
31
+
32
+ reconstruction = scene.reconstruction
33
+ xyz = np.stack([pt3d.xyz for pt3d in reconstruction.points3D.values()])
34
+ rgb = np.stack([pt3d.color for pt3d in reconstruction.points3D.values()])
35
+
36
+ R, t, K = [], [], []
37
+ image_id_to_idx = {}
38
+ for idx in range(scene.num_images):
39
+ image = reconstruction.find_image_with_name(scene.image_name(idx))
40
+ cam_from_world = image.cam_from_world
41
+ if callable(cam_from_world):
42
+ cam_from_world = cam_from_world()
43
+ R.append(cam_from_world.rotation.matrix())
44
+ t.append(cam_from_world.translation)
45
+ camera = reconstruction.cameras[image.camera_id]
46
+ K.append(camera.calibration_matrix())
47
+ image_id_to_idx[image.image_id] = idx
48
+
49
+ ade_width, ade_height = ade[idx].shape[1], ade[idx].shape[0]
50
+ gestalt_width, gestalt_height = gestalt[idx].shape[1], gestalt[idx].shape[0]
51
+ if ade_width != gestalt_width or ade_height != gestalt_height:
52
+ raise ValueError(f"ADE/Gestalt dimension mismatch for image {image.name} in scene {scene.order_id}")
53
+ if abs(ade_width - camera.width) > 1 or abs(ade_height - camera.height) > 1:
54
+ raise ValueError(f"Camera/ADE dimension mismatch for image {image.name} in scene {scene.order_id}")
55
+ R, t, K = np.stack(R), np.stack(t), np.stack(K)
56
+
57
+ X = (xyz @ R.transpose(0, 2, 1) + t[:, None]) @ K.transpose(0, 2, 1)
58
+ xy = X[..., :2] / X[..., 2:3]
59
+ xy = np.round(xy).astype(int)
60
+ ade_size = np.array([ade[idx].shape for idx in range(scene.num_images)])
61
+ xy = np.clip(xy, 0, ade_size[:, None, [1, 0]] - 1)
62
+
63
+ def most_common_entry(rgbs):
64
+ counts = {}
65
+ for rgb_val in rgbs:
66
+ key = tuple(rgb_val)
67
+ counts[key] = counts.get(key, 0) + 1
68
+ return np.array(max(counts, key=counts.get))
69
+
70
+ ade_rgb, gestalt_rgb = [], []
71
+ for point_idx, pt3d in enumerate(reconstruction.points3D.values()):
72
+ ade_rgbs, gestalt_rgbs = [], []
73
+ for elem in pt3d.track.elements:
74
+ idx = image_id_to_idx[elem.image_id]
75
+ x, y = xy[idx, point_idx]
76
+ ade_rgbs.append(ade[idx][y, x])
77
+ gestalt_rgbs.append(gestalt[idx][y, x])
78
+ ade_rgb.append(most_common_entry(ade_rgbs))
79
+ gestalt_rgb.append(most_common_entry(gestalt_rgbs))
80
+ ade_rgb = np.stack(ade_rgb)
81
+ gestalt_rgb = np.stack(gestalt_rgb)
82
+
83
+ mask_colors = np.array([gestalt_color_mapping[cls] for cls in ("unclassified", "unknown")], dtype=np.uint8)
84
+ mask = np.any(np.all(gestalt_rgb[:, None, :] == mask_colors[None, :, :], axis=-1), axis=1)
85
+ return xyz[~mask], rgb[~mask], ade_rgb[~mask], gestalt_rgb[~mask]
86
+
87
+
88
+ def predict_wireframe_v2(
89
+ scene: Scene,
90
+ model: WireframeBase,
91
+ device: str,
92
+ pt_type: str = "colmap",
93
+ num_points: int = 7168,
94
+ score_threshold: float = 0.9,
95
+ merge_distance_threshold: float = 0.5,
96
+ min_edge_length: float = 0.05,
97
+ max_edge_length: float = 100.0,
98
+ remove_solitary_edges: bool = False,
99
+ filter_by_length: bool = False,
100
+ project_near_horizontal_edges: bool = False,
101
+ snap_to_principal_directions: bool = False,
102
+ horizontal_angle_threshold_deg: float = 5.0,
103
+ principal_direction_angle_threshold_deg: float = 5.0,
104
+
105
+ intersection_angle_threshold_deg: float | None = None,
106
+ gap_fill_edges: bool = False,
107
+ gap_fill_score_threshold: float = 0.2,
108
+ complete_symmetric_edges: bool = False,
109
+ symmetric_edge_distance_threshold: float = 0.2,
110
+ merge_method: str = "distance",
111
+ feature_alpha: float = 0.95,
112
+ ) -> tuple[np.ndarray, np.ndarray]:
113
+ assert pt_type in ("colmap", "monodepth", "both")
114
+
115
+ if pt_type == "colmap":
116
+ points, colors, ade_colors, gestalt_colors = get_colmap_points(scene)
117
+ xyz = torch.from_numpy(points).float()
118
+ features = colors_to_features(gestalt_colors, ade_colors, rgb=colors, one_hot=False)
119
+ min_xyz, max_xyz, q_diff = compute_norm_params(xyz)
120
+ xyz = (xyz - min_xyz) / q_diff
121
+ indices = torch.from_numpy(sample_points(gestalt_colors, num_points, weight_vertex=100.0, weight_edge=10.0))
122
+ xyz = xyz[indices]
123
+ features = features[indices]
124
+ else:
125
+ raise ValueError("Only pt_type='colmap' supported in this implementation.")
126
+
127
+ xyz, features = xyz.to(device), features.to(device)
128
+ do_gap_fill = gap_fill_edges and gap_fill_score_threshold < score_threshold
129
+ inference_threshold = gap_fill_score_threshold if do_gap_fill else score_threshold
130
+ results = model.inference(xyz, features, threshold=inference_threshold)
131
+
132
+ verts, edges = results["vertices"], results["edges"]
133
+ min_xyz_np, max_xyz_np = min_xyz.numpy(), max_xyz.numpy()
134
+ verts = verts * (max_xyz_np - min_xyz_np) + min_xyz_np
135
+
136
+ candidate_edge_points = None
137
+ if do_gap_fill:
138
+ scores = results["scores"]
139
+ edge_points = verts[edges]
140
+ high_confidence = scores > score_threshold
141
+ gap_fill_candidates = (scores > gap_fill_score_threshold) & (scores <= score_threshold)
142
+ verts = edge_points[high_confidence].reshape(-1, 3)
143
+ edges = np.arange(len(verts), dtype=edges.dtype).reshape(-1, 2)
144
+ candidate_edge_points = edge_points[gap_fill_candidates]
145
+
146
+ if merge_method == "auto":
147
+ merge_method = "feature" if "vertex_feats" in results else "distance"
148
+ if merge_method == "feature" and "vertex_feats" not in results:
149
+ merge_method = "distance"
150
+
151
+ if merge_method == "feature":
152
+ vertex_feats = np.asarray(results["vertex_feats"], dtype=np.float32)
153
+ edge_scores = np.asarray(results["scores"], dtype=np.float32)
154
+ if do_gap_fill:
155
+ vertex_feats = vertex_feats.reshape(-1, 2, vertex_feats.shape[-1])[high_confidence].reshape(-1, vertex_feats.shape[-1])
156
+ edge_scores = edge_scores[high_confidence]
157
+ verts, edges, _ = merge_vertices_with_features(
158
+ verts, edges, vertex_feats,
159
+ alpha=feature_alpha,
160
+ distance_threshold=merge_distance_threshold,
161
+ vertex_scores=np.repeat(edge_scores, 2),
162
+ )
163
+ if complete_symmetric_edges:
164
+ verts, edges = add_edges_by_translated_edge_symmetry(verts, edges, distance_threshold=symmetric_edge_distance_threshold)
165
+ if filter_by_length:
166
+ verts, edges = filter_edges_by_length(verts, edges, min_edge_length, max_edge_length)
167
+ if project_near_horizontal_edges:
168
+ verts, edges = project_near_horizontal_edges_to_xz_plane(verts, edges, horizontal_angle_threshold_deg=horizontal_angle_threshold_deg, principal_direction_angle_threshold_deg=principal_direction_angle_threshold_deg)
169
+ if snap_to_principal_directions:
170
+ verts, edges = snap_edges_to_principal_xz_directions(verts, edges, horizontal_angle_threshold_deg=horizontal_angle_threshold_deg, principal_direction_angle_threshold_deg=principal_direction_angle_threshold_deg)
171
+ if remove_solitary_edges:
172
+ verts, edges = remove_solitary_edges_from_wireframe(verts, edges)
173
+ if candidate_edge_points is not None:
174
+ verts, edges = add_gap_fill_edges_from_candidates(verts, edges, candidate_edge_points, merge_distance_threshold)
175
+ else:
176
+ verts, edges = post_process_wireframe(
177
+ verts, edges, merge_distance_threshold,
178
+ intersection_angle_threshold_deg=intersection_angle_threshold_deg,
179
+ remove_solitary_edges=remove_solitary_edges,
180
+ min_edge_length=min_edge_length,
181
+ max_edge_length=max_edge_length,
182
+ filter_by_length=filter_by_length,
183
+ project_near_horizontal_edges=project_near_horizontal_edges,
184
+ snap_to_principal_directions=snap_to_principal_directions,
185
+ horizontal_angle_threshold_deg=horizontal_angle_threshold_deg,
186
+ principal_direction_angle_threshold_deg=principal_direction_angle_threshold_deg,
187
+ gap_fill_candidate_edge_points=candidate_edge_points,
188
+ complete_symmetric_edges=complete_symmetric_edges,
189
+ symmetric_edge_distance_threshold=symmetric_edge_distance_threshold,
190
+ )
191
+
192
+ return verts, edges
193
+
194
+
195
+ def predict_wireframe_v2_tta(
196
+ scene: Scene,
197
+ model: WireframeBase,
198
+ device: str,
199
+ pt_type: str = "colmap",
200
+ num_points: int = 7168,
201
+ score_threshold: float = 0.9,
202
+ merge_distance_threshold: float = 0.5,
203
+
204
+ n_rotations: int = 4,
205
+ ) -> tuple[np.ndarray, np.ndarray]:
206
+ """Test-Time Augmentation: predict over N evenly-spaced Y-axis rotations and merge.
207
+
208
+ Rotates the point cloud n_rotations times, runs inference each time,
209
+ un-rotates predictions back to world space, then merges all predictions
210
+ via vertex proximity deduplication.
211
+ """
212
+ assert pt_type == "colmap", "TTA only supports pt_type='colmap'"
213
+
214
+ points, colors, ade_colors, gestalt_colors = get_colmap_points(scene)
215
+ xyz_world = torch.from_numpy(points).float()
216
+ features = colors_to_features(gestalt_colors, ade_colors, rgb=colors, one_hot=False)
217
+
218
+ indices = torch.from_numpy(
219
+ sample_points(gestalt_colors, num_points, weight_vertex=100.0, weight_edge=10.0)
220
+ ).long()
221
+ xyz_sampled = xyz_world[indices]
222
+ features_sampled = features[indices]
223
+ centroid = xyz_sampled.mean(dim=0).numpy()
224
+
225
+ all_verts: list[np.ndarray] = []
226
+ all_edges: list[np.ndarray] = []
227
+ vert_offset = 0
228
+
229
+ for k in range(n_rotations):
230
+ theta = k * 2.0 * math.pi / n_rotations
231
+ R = _rotation_matrix_y(theta)
232
+
233
+ xyz_np = xyz_sampled.numpy()
234
+ xyz_rot_np = (xyz_np - centroid) @ R.T + centroid
235
+ xyz_rot = torch.from_numpy(xyz_rot_np).float()
236
+
237
+ min_xyz, max_xyz, q_diff = compute_norm_params(xyz_rot)
238
+ xyz_norm = (xyz_rot - min_xyz) / q_diff
239
+
240
+ results = model.inference(xyz_norm.to(device), features_sampled.to(device), threshold=score_threshold)
241
+ verts_norm = results["vertices"]
242
+ edges = results["edges"]
243
+
244
+ if len(edges) == 0:
245
+ continue
246
+
247
+ verts_rot_world = verts_norm * q_diff.numpy() + min_xyz.numpy()
248
+ verts_orig = (verts_rot_world - centroid) @ R.T + centroid # R^T = R^{-1}
249
+
250
+ all_verts.append(verts_orig)
251
+ all_edges.append(edges + vert_offset)
252
+ vert_offset += len(verts_orig)
253
+
254
+ if not all_verts:
255
+ return np.zeros((0, 3), dtype=np.float32), np.zeros((0, 2), dtype=np.int64)
256
+
257
+ final_verts, final_edges = post_process_wireframe(
258
+ np.concatenate(all_verts, axis=0),
259
+ np.concatenate(all_edges, axis=0),
260
+ merge_distance_threshold=merge_distance_threshold,
261
+ )
262
+ return final_verts, final_edges