junaid-simamdigital commited on
Commit
bed8826
·
verified ·
1 Parent(s): 10bfddb

Initial ZeroGPU Simam3D runtime

Browse files
Files changed (1) hide show
  1. simam3d_core.py +612 -0
simam3d_core.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure NumPy geometry utilities for Simam3D.
2
+
3
+ This module intentionally has no Torch, Gradio, or CUDA dependency. It is the
4
+ testable contract between model adapters and the export/UI layer.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class FusionResult:
17
+ points: np.ndarray
18
+ colors: np.ndarray
19
+ weights: np.ndarray
20
+ source_views: np.ndarray
21
+ source_masks: np.ndarray
22
+
23
+
24
+ def normalize_map(values: np.ndarray) -> np.ndarray:
25
+ values = np.asarray(values, dtype=np.float32)
26
+ finite = np.isfinite(values)
27
+ if not finite.any():
28
+ return np.zeros_like(values, dtype=np.float32)
29
+ lo = float(values[finite].min())
30
+ hi = float(values[finite].max())
31
+ return np.clip(np.nan_to_num((values - lo) / max(hi - lo, 1e-6)), 0.0, 1.0)
32
+
33
+
34
+ def analyze_light_field(colors: np.ndarray) -> dict[str, float | str]:
35
+ """Estimate image-space illumination cues from an RGB image.
36
+
37
+ This is an auditable cue detector, not physical inverse rendering. It uses
38
+ luminance, contrast, and the centroid of bright pixels to provide a stable
39
+ lighting hypothesis for the UI and future learned relighting work.
40
+ """
41
+ rgb = np.asarray(colors, dtype=np.float32)
42
+ if rgb.ndim != 3 or rgb.shape[2] < 3 or min(rgb.shape[:2]) < 2:
43
+ raise ValueError("colors must have shape HxWx3 or HxWx4")
44
+ rgb = np.clip(rgb[..., :3], 0.0, 255.0) / 255.0
45
+ luminance = 0.2126 * rgb[..., 0] + 0.7152 * rgb[..., 1] + 0.0722 * rgb[..., 2]
46
+ mean = float(luminance.mean())
47
+ contrast = float(luminance.std())
48
+ bright_threshold = float(np.percentile(luminance, 90))
49
+ bright = luminance >= max(bright_threshold, 0.65)
50
+ yy, xx = np.mgrid[0:luminance.shape[0], 0:luminance.shape[1]]
51
+ mass = luminance * bright
52
+ total = float(mass.sum())
53
+ if total > 1e-6:
54
+ cx = float((xx * mass).sum() / total / max(luminance.shape[1] - 1, 1) * 2.0 - 1.0)
55
+ cy = float(1.0 - (yy * mass).sum() / total / max(luminance.shape[0] - 1, 1) * 2.0)
56
+ else:
57
+ cx = cy = 0.0
58
+ highlight_fraction = float(bright.mean())
59
+ shadow_fraction = float((luminance <= np.percentile(luminance, 10)).mean())
60
+ azimuth = float(np.degrees(np.arctan2(cx, max(cy, 1e-6))))
61
+ elevation = float(np.clip(35.0 + 45.0 * cy, 5.0, 85.0))
62
+ if contrast < 0.08:
63
+ label = "soft / low-contrast light"
64
+ elif highlight_fraction < 0.03 and shadow_fraction > 0.18:
65
+ label = "directional light with strong shadow cues"
66
+ else:
67
+ label = "directional light with diffuse fill"
68
+ confidence = float(np.clip(contrast * 3.0 + min(highlight_fraction * 2.0, 0.25), 0.0, 1.0))
69
+ return {
70
+ "lighting_label": label,
71
+ "mean_luminance": mean,
72
+ "contrast": contrast,
73
+ "highlight_fraction": highlight_fraction,
74
+ "shadow_fraction": shadow_fraction,
75
+ "bright_centroid_x": cx,
76
+ "bright_centroid_y": cy,
77
+ "estimated_azimuth_deg": azimuth,
78
+ "estimated_elevation_deg": elevation,
79
+ "detector_confidence": confidence,
80
+ }
81
+
82
+
83
+ def estimate_depth_light(depth: np.ndarray, colors: np.ndarray) -> dict[str, float | str]:
84
+ """Estimate a camera-space light direction from depth-derived normals.
85
+
86
+ This is a low-cost photometric heuristic. It is useful for ranking light
87
+ hypotheses and checking generated views, but it is not physical inverse
88
+ rendering and cannot disambiguate albedo from illumination by itself.
89
+ """
90
+ depth = np.asarray(depth, dtype=np.float32)
91
+ rgb = np.asarray(colors, dtype=np.float32)
92
+ if depth.ndim != 2 or rgb.ndim != 3 or rgb.shape[:2] != depth.shape or rgb.shape[2] < 3:
93
+ raise ValueError("depth must be HxW and colors must be matching HxWx3")
94
+ h, w = depth.shape
95
+ z = 1.0 - normalize_map(depth)
96
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
97
+ x = (xx / max(w - 1, 1) - 0.5) * 2.0
98
+ y = (0.5 - yy / max(h - 1, 1)) * 2.0
99
+ points = np.stack([x, y, z], axis=-1)
100
+ dx = np.gradient(points, axis=1)
101
+ dy = np.gradient(points, axis=0)
102
+ normals = np.cross(dx, dy)
103
+ lengths = np.linalg.norm(normals, axis=-1, keepdims=True)
104
+ normals = normals / np.maximum(lengths, 1e-6)
105
+ normals = np.where(normals[..., 2:3] < 0.0, -normals, normals)
106
+ luminance = (0.2126 * rgb[..., 0] + 0.7152 * rgb[..., 1] + 0.0722 * rgb[..., 2]) / 255.0
107
+ signal = np.clip(luminance - float(luminance.mean()), 0.0, None)
108
+ total = float(signal.sum())
109
+ if total <= 1e-6:
110
+ direction = np.array([0.0, 0.0, 1.0], dtype=np.float32)
111
+ confidence = 0.0
112
+ else:
113
+ direction = (normals * signal[..., None]).sum(axis=(0, 1)) / total
114
+ direction = direction / max(float(np.linalg.norm(direction)), 1e-6)
115
+ confidence = float(np.clip(np.linalg.norm((normals * signal[..., None]).sum(axis=(0, 1))) / total, 0.0, 1.0))
116
+ azimuth = float(np.degrees(np.arctan2(float(direction[0]), float(direction[2]))))
117
+ elevation = float(np.degrees(np.arcsin(np.clip(float(direction[1]), -1.0, 1.0))))
118
+ return {
119
+ "light_direction_x": float(direction[0]),
120
+ "light_direction_y": float(direction[1]),
121
+ "light_direction_z": float(direction[2]),
122
+ "estimated_azimuth_deg": azimuth,
123
+ "estimated_elevation_deg": elevation,
124
+ "photometric_confidence": confidence,
125
+ "status": "depth-normal photometric heuristic; albedo and exposure are confounds",
126
+ }
127
+
128
+
129
+ def deterministic_demo_depth(colors: np.ndarray) -> np.ndarray:
130
+ """Create an explicitly non-AI depth-like map for export-pipeline smoke tests."""
131
+ rgb = np.asarray(colors, dtype=np.float32)
132
+ if rgb.ndim != 3 or rgb.shape[2] < 3:
133
+ raise ValueError("colors must have shape HxWx3 or HxWx4")
134
+ luminance = 0.2126 * rgb[..., 0] + 0.7152 * rgb[..., 1] + 0.0722 * rgb[..., 2]
135
+ # Invert brightness only to create stable synthetic geometry; this has no
136
+ # semantic or metric meaning and must remain labelled as demo output.
137
+ return (255.0 - luminance).astype(np.float32)
138
+
139
+
140
+ def classify_scene_hypothesis(text: str | None) -> dict[str, str | list[str]]:
141
+ """Turn the user's reveal guess into explicit, inspectable semantic cues."""
142
+ raw = (text or "").strip()
143
+ normalized = " ".join(raw.split())
144
+ lower = normalized.lower()
145
+ cue_groups = {
146
+ "outdoor": ("sky", "street", "garden", "forest", "mountain", "building", "road"),
147
+ "indoor": ("room", "wall", "kitchen", "office", "hallway", "inside"),
148
+ "person": ("person", "face", "body", "portrait", "human"),
149
+ "object": ("object", "chair", "car", "shoe", "bottle", "product", "box"),
150
+ "nature": ("tree", "plant", "garden", "water", "animal", "cloud", "rock"),
151
+ }
152
+ cues = [name for name, words in cue_groups.items() if any(word in lower for word in words)]
153
+ return {
154
+ "user_guess": normalized or "No prior guess supplied",
155
+ "semantic_cues": cues or ["unspecified"],
156
+ "status": "user hypothesis only; not verified hidden content",
157
+ }
158
+
159
+
160
+ def reveal_uncertainty(depth: np.ndarray, confidence: np.ndarray | None = None) -> np.ndarray:
161
+ """Build a visible-space uncertainty map for deciding where to inspect next.
162
+
163
+ Low confidence and strong depth discontinuities are useful acquisition cues,
164
+ but this map does not assert what exists outside the camera's field of view.
165
+ """
166
+ depth = np.asarray(depth, dtype=np.float32)
167
+ if depth.ndim != 2:
168
+ raise ValueError("depth must be a 2-D map")
169
+ normalized = normalize_map(depth)
170
+ gy, gx = np.gradient(normalized)
171
+ edges = np.sqrt(gx * gx + gy * gy)
172
+ edges = normalize_map(edges)
173
+ if confidence is None:
174
+ conf = np.ones_like(normalized)
175
+ else:
176
+ conf = np.asarray(confidence, dtype=np.float32)
177
+ if conf.shape != depth.shape:
178
+ conf = np.ones_like(normalized)
179
+ conf = np.nan_to_num(conf, nan=0.0, posinf=0.0, neginf=0.0)
180
+ conf = np.clip(conf, 0.0, None)
181
+ peak = float(conf.max()) if conf.size else 0.0
182
+ conf = conf / peak if peak > 1e-6 else np.zeros_like(normalized)
183
+ return np.clip(0.7 * (1.0 - conf) + 0.3 * edges, 0.0, 1.0).astype(np.float32)
184
+
185
+
186
+ def next_view_plan(view_count: int) -> list[dict[str, float | str]]:
187
+ """Suggest deterministic yaw targets that fill the largest view gaps."""
188
+ if view_count < 1:
189
+ raise ValueError("view_count must be positive")
190
+ existing = np.linspace(0.0, 360.0, view_count, endpoint=False)
191
+ targets = [180.0, 90.0, 270.0, 45.0, 315.0]
192
+ suggestions = []
193
+ for yaw in targets:
194
+ distance = float(np.min(np.abs(((existing - yaw + 180.0) % 360.0) - 180.0)))
195
+ suggestions.append({"yaw_deg": yaw, "gap_from_existing_deg": distance, "reason": "largest unsupported azimuth"})
196
+ return sorted(suggestions, key=lambda item: (-float(item["gap_from_existing_deg"]), float(item["yaw_deg"])))
197
+
198
+
199
+ def orbit_project_points(points: np.ndarray, yaw_deg: float) -> tuple[np.ndarray, np.ndarray]:
200
+ """Project reconstructed points to a normalized orbit view for previews."""
201
+ points = np.asarray(points, dtype=np.float32)
202
+ if points.ndim != 2 or points.shape[1] != 3:
203
+ raise ValueError("points must have shape Nx3")
204
+ angle = np.deg2rad(float(yaw_deg))
205
+ cosine, sine = np.cos(angle), np.sin(angle)
206
+ rotation = np.array([[cosine, 0.0, -sine], [0.0, 1.0, 0.0], [sine, 0.0, cosine]], dtype=np.float32)
207
+ view = points @ rotation.T
208
+ extent = max(float(np.max(np.abs(view[:, :2]))) if len(view) else 0.0, 1e-6)
209
+ xy = np.clip(view[:, :2] / extent, -1.0, 1.0)
210
+ return xy.astype(np.float32), view[:, 2].astype(np.float32)
211
+
212
+
213
+ def default_intrinsics(width: int, height: int) -> np.ndarray:
214
+ focal = float(max(width, height))
215
+ return np.array(
216
+ [[focal, 0.0, width / 2.0], [0.0, focal, height / 2.0], [0.0, 0.0, 1.0]],
217
+ dtype=np.float32,
218
+ )
219
+
220
+
221
+ def prepare_intrinsics(matrix: np.ndarray | None, width: int, height: int) -> np.ndarray:
222
+ """Validate intrinsics and convert normalized matrices to pixel units."""
223
+ if matrix is None:
224
+ return default_intrinsics(width, height)
225
+ k = np.asarray(matrix, dtype=np.float32).copy()
226
+ if k.shape != (3, 3) or not np.isfinite(k).all() or abs(float(k[2, 2])) < 1e-6:
227
+ return default_intrinsics(width, height)
228
+ # The V2 placeholder is identity, which means unknown rather than a real
229
+ # camera. Normalized camera matrices commonly use fx/fy and cx/cy in [0, 1].
230
+ if np.allclose(k, np.eye(3, dtype=np.float32)):
231
+ return default_intrinsics(width, height)
232
+ if abs(float(k[0, 0])) <= 2.0 and abs(float(k[1, 1])) <= 2.0:
233
+ k[0, :] *= width
234
+ k[1, :] *= height
235
+ if abs(float(k[0, 0])) < 1e-6 or abs(float(k[1, 1])) < 1e-6:
236
+ return default_intrinsics(width, height)
237
+ return k
238
+
239
+
240
+ def ensure_pose(matrix: np.ndarray | None) -> np.ndarray:
241
+ if matrix is None:
242
+ return np.eye(4, dtype=np.float32)
243
+ pose = np.asarray(matrix, dtype=np.float32)
244
+ if pose.shape == (3, 4):
245
+ pose = np.vstack([pose, [0.0, 0.0, 0.0, 1.0]])
246
+ if pose.shape != (4, 4) or not np.isfinite(pose).all():
247
+ return np.eye(4, dtype=np.float32)
248
+ return pose
249
+
250
+
251
+ def synthetic_orbit_poses(view_count: int, radius: float = 0.35) -> np.ndarray:
252
+ """Return a deterministic orbit prior for views without camera metadata.
253
+
254
+ These are world-to-camera poses for visualization/fusion only. They are not
255
+ a substitute for calibrated camera poses and are labeled as synthetic by
256
+ the application manifest.
257
+ """
258
+ if view_count < 1:
259
+ return np.empty((0, 4, 4), dtype=np.float32)
260
+ if view_count == 1:
261
+ return np.eye(4, dtype=np.float32)[None, ...]
262
+ poses = []
263
+ up = np.array([0.0, 1.0, 0.0], dtype=np.float32)
264
+ for index in range(view_count):
265
+ angle = 2.0 * np.pi * index / max(view_count, 1)
266
+ position = np.array([radius * np.sin(angle), 0.0, radius * np.cos(angle)], dtype=np.float32)
267
+ forward = -position / max(float(np.linalg.norm(position)), 1e-6)
268
+ right = np.cross(up, forward)
269
+ right /= max(float(np.linalg.norm(right)), 1e-6)
270
+ true_up = np.cross(forward, right)
271
+ camera_to_world = np.eye(4, dtype=np.float32)
272
+ camera_to_world[:3, :3] = np.stack([right, true_up, forward], axis=1)
273
+ camera_to_world[:3, 3] = position
274
+ poses.append(np.linalg.inv(camera_to_world).astype(np.float32))
275
+ return np.stack(poses, axis=0)
276
+
277
+
278
+ def normalize_prediction_contract(prediction, view_count: int):
279
+ """Validate and normalize the official DA3 Prediction output contract."""
280
+ depth = np.asarray(getattr(prediction, "depth", None), dtype=np.float32)
281
+ if depth.ndim == 2 and view_count == 1:
282
+ depth = depth[None, ...]
283
+ if depth.ndim != 3 or depth.shape[0] != view_count or not np.isfinite(depth).all():
284
+ raise ValueError(f"DA3 depth must have shape ({view_count}, H, W), got {depth.shape}")
285
+ raw_confidence = getattr(prediction, "conf", None)
286
+ if raw_confidence is None:
287
+ confidence = np.ones_like(depth, dtype=np.float32)
288
+ confidence_source = "baseline_uniform"
289
+ else:
290
+ confidence = np.asarray(raw_confidence, dtype=np.float32)
291
+ if confidence.ndim == 2 and view_count == 1:
292
+ confidence = confidence[None, ...]
293
+ if confidence.shape != depth.shape or not np.isfinite(confidence).all():
294
+ raise ValueError(f"DA3 confidence must match depth shape {depth.shape}, got {confidence.shape}")
295
+ confidence_source = "depth_anything_3"
296
+ raw_extrinsics = getattr(prediction, "extrinsics", None)
297
+ if raw_extrinsics is not None:
298
+ extrinsics = np.asarray(raw_extrinsics, dtype=np.float32)
299
+ valid_pose_shapes = {(view_count, 3, 4), (view_count, 4, 4)}
300
+ if extrinsics.shape not in valid_pose_shapes or not np.isfinite(extrinsics).all():
301
+ raise ValueError(f"DA3 extrinsics have invalid shape {extrinsics.shape}")
302
+ pose_source = "depth_anything_3"
303
+ else:
304
+ extrinsics = synthetic_orbit_poses(view_count)
305
+ pose_source = "synthetic_orbit_prior"
306
+ raw_intrinsics = getattr(prediction, "intrinsics", None)
307
+ if raw_intrinsics is not None:
308
+ intrinsics = np.asarray(raw_intrinsics, dtype=np.float32)
309
+ if intrinsics.shape != (view_count, 3, 3) or not np.isfinite(intrinsics).all():
310
+ raise ValueError(f"DA3 intrinsics have invalid shape {intrinsics.shape}")
311
+ else:
312
+ intrinsics = np.repeat(np.eye(3, dtype=np.float32)[None, ...], view_count, axis=0)
313
+ return depth, confidence, extrinsics, intrinsics, confidence_source, pose_source
314
+
315
+
316
+ def project_world_points(
317
+ points: np.ndarray,
318
+ intrinsics: np.ndarray | None,
319
+ extrinsics: np.ndarray | None,
320
+ width: int,
321
+ height: int,
322
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
323
+ """Project world-space points into a view and return pixels, depth, validity."""
324
+ points = np.asarray(points, dtype=np.float32)
325
+ if points.ndim != 2 or points.shape[1] != 3:
326
+ raise ValueError("points must have shape Nx3")
327
+ pose = ensure_pose(extrinsics)
328
+ camera = (pose @ np.c_[points, np.ones(len(points), dtype=np.float32)].T).T[:, :3]
329
+ k = prepare_intrinsics(intrinsics, width, height)
330
+ positive = camera[:, 2] > 1e-6
331
+ pixels = np.full((len(points), 2), np.nan, dtype=np.float32)
332
+ pixels[positive, 0] = k[0, 0] * camera[positive, 0] / camera[positive, 2] + k[0, 2]
333
+ pixels[positive, 1] = k[1, 1] * camera[positive, 1] / camera[positive, 2] + k[1, 2]
334
+ inside = positive & (pixels[:, 0] >= 0.0) & (pixels[:, 0] < width) & (pixels[:, 1] >= 0.0) & (pixels[:, 1] < height)
335
+ return pixels, camera[:, 2].astype(np.float32), inside
336
+
337
+
338
+ def reprojection_consistency(
339
+ points: np.ndarray,
340
+ depth: np.ndarray,
341
+ intrinsics: np.ndarray | None,
342
+ extrinsics: np.ndarray | None,
343
+ ) -> dict[str, float]:
344
+ """Compare fused-point depth against a view's relative depth prediction."""
345
+ depth = np.asarray(depth, dtype=np.float32)
346
+ if depth.ndim != 2:
347
+ raise ValueError("depth must be a 2-D map")
348
+ height, width = depth.shape
349
+ pixels, point_depth, inside = project_world_points(
350
+ points, intrinsics, extrinsics, width, height
351
+ )
352
+ if not inside.any():
353
+ return {"coverage": 0.0, "mean_absolute_error": 0.0, "median_absolute_error": 0.0}
354
+ raster = np.full((height, width), np.nan, dtype=np.float32)
355
+ pixel_x = np.clip(np.rint(pixels[inside, 0]).astype(np.int64), 0, width - 1)
356
+ pixel_y = np.clip(np.rint(pixels[inside, 1]).astype(np.int64), 0, height - 1)
357
+ for x, y, value in zip(pixel_x, pixel_y, point_depth[inside]):
358
+ if not np.isfinite(raster[y, x]) or value < raster[y, x]:
359
+ raster[y, x] = value
360
+ valid = np.isfinite(raster)
361
+ if not valid.any():
362
+ return {"coverage": 0.0, "mean_absolute_error": 0.0, "median_absolute_error": 0.0}
363
+ target = 1.0 - normalize_map(depth)
364
+ error = np.abs(raster[valid] - target[valid])
365
+ return {
366
+ "coverage": float(valid.mean()),
367
+ "mean_absolute_error": float(error.mean()),
368
+ "median_absolute_error": float(np.median(error)),
369
+ }
370
+
371
+
372
+ def depth_to_camera_points(
373
+ depth: np.ndarray,
374
+ intrinsics: np.ndarray | None = None,
375
+ confidence: np.ndarray | None = None,
376
+ ) -> tuple[np.ndarray, np.ndarray]:
377
+ """Project a depth map into camera-space points and return point weights."""
378
+ depth = np.asarray(depth, dtype=np.float32)
379
+ if depth.ndim != 2:
380
+ raise ValueError(f"depth must be HxW, got {depth.shape}")
381
+ height, width = depth.shape
382
+ k = prepare_intrinsics(intrinsics, width, height)
383
+ yy, xx = np.mgrid[0:height, 0:width]
384
+ # Depth Anything outputs relative depth; the scaffold uses inverse-depth
385
+ # convention consistently with the GLB/PLY exporters (higher prediction
386
+ # values place a point closer to the camera). Metric scale is not claimed.
387
+ z = 1.0 - normalize_map(depth)
388
+ z = np.clip(z, 0.02, 1.0)
389
+ points = np.stack(
390
+ [(xx - k[0, 2]) / max(float(k[0, 0]), 1e-6) * z,
391
+ (yy - k[1, 2]) / max(float(k[1, 1]), 1e-6) * z,
392
+ z],
393
+ axis=-1,
394
+ ).reshape(-1, 3)
395
+ if confidence is None:
396
+ weights = np.ones((height, width), dtype=np.float32)
397
+ else:
398
+ weights = np.nan_to_num(np.asarray(confidence, dtype=np.float32), nan=0.0)
399
+ if weights.shape != (height, width):
400
+ weights = np.ones((height, width), dtype=np.float32)
401
+ weights = np.clip(weights, 0.0, None)
402
+ peak = float(weights.max()) if weights.size else 0.0
403
+ # Preserve absolute confidence ratios across views: min-max scaling
404
+ # would turn a valid 0.5 confidence into zero when it is the minimum.
405
+ weights = weights / peak if peak > 1e-6 else np.zeros_like(weights)
406
+ return points, weights.reshape(-1)
407
+
408
+
409
+ def fuse_point_views(
410
+ views: list[tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray | None, np.ndarray]],
411
+ voxel_size: float = 0.02,
412
+ max_points: int = 150_000,
413
+ ) -> FusionResult:
414
+ """Fuse `(depth, confidence, intrinsics, extrinsics, colors)` views.
415
+
416
+ Extrinsics are interpreted as world-to-camera, matching DA3's API. Fusion
417
+ is deterministic: points are grouped into voxels and confidence-weighted
418
+ centroids/colors are retained, then capped by voxel confidence.
419
+ """
420
+ points_all, colors_all, weights_all, sources_all, masks_all = [], [], [], [], []
421
+ for source_view, (depth, confidence, intrinsics, extrinsics, colors) in enumerate(views):
422
+ depth = np.asarray(depth, dtype=np.float32)
423
+ colors = np.asarray(colors, dtype=np.uint8)
424
+ if colors.shape[:2] != depth.shape or colors.shape[-1] < 3:
425
+ raise ValueError("colors must have shape HxWx3 or HxWx4 matching depth")
426
+ camera_points, weights = depth_to_camera_points(depth, intrinsics, confidence)
427
+ pose = ensure_pose(extrinsics)
428
+ world_points = (np.linalg.inv(pose) @ np.c_[camera_points, np.ones(len(camera_points))].T).T[:, :3]
429
+ colors_all.append(colors[..., :3].reshape(-1, 3))
430
+ points_all.append(world_points)
431
+ weights_all.append(weights)
432
+ sources_all.append(np.full(len(weights), source_view, dtype=np.int32))
433
+ masks_all.append(np.full(len(weights), 1 << source_view, dtype=np.int32))
434
+ if not points_all:
435
+ empty = np.empty((0, 3), dtype=np.float32)
436
+ return FusionResult(
437
+ empty, np.empty((0, 3), dtype=np.uint8), np.empty((0,), dtype=np.float32),
438
+ np.empty((0,), dtype=np.int32), np.empty((0,), dtype=np.int32)
439
+ )
440
+ if len(views) > 30:
441
+ raise ValueError("At most 30 views are supported by the signed int32 provenance bitmask")
442
+ points = np.concatenate(points_all).astype(np.float32)
443
+ colors = np.concatenate(colors_all).astype(np.uint8)
444
+ weights = np.concatenate(weights_all).astype(np.float32)
445
+ source_views = np.concatenate(sources_all).astype(np.int32)
446
+ source_masks = np.concatenate(masks_all).astype(np.int32)
447
+ valid = np.isfinite(points).all(axis=1) & np.isfinite(weights) & (weights > 0)
448
+ points, colors, weights = points[valid], colors[valid], weights[valid]
449
+ source_views, source_masks = source_views[valid], source_masks[valid]
450
+ if voxel_size > 0 and len(points):
451
+ voxels = np.floor(points / voxel_size).astype(np.int64)
452
+ unique_voxels, inverse = np.unique(voxels, axis=0, return_inverse=True)
453
+ grouped_points = np.zeros((len(unique_voxels), 3), dtype=np.float64)
454
+ grouped_colors = np.zeros((len(unique_voxels), 3), dtype=np.float64)
455
+ grouped_weight = np.zeros(len(unique_voxels), dtype=np.float64)
456
+ np.add.at(grouped_points, inverse, points * weights[:, None])
457
+ np.add.at(grouped_colors, inverse, colors * weights[:, None])
458
+ np.add.at(grouped_weight, inverse, weights)
459
+ counts = np.bincount(inverse, minlength=len(unique_voxels)).astype(np.float64)
460
+ # Pick the strongest individual observation as an auditable provenance
461
+ # pointer for each voxel; full multi-source lineage remains future work.
462
+ raw_order = np.argsort(-weights, kind="stable")
463
+ _, first_source = np.unique(inverse[raw_order], return_index=True)
464
+ source_by_voxel = np.zeros(len(unique_voxels), dtype=np.int32)
465
+ source_by_voxel[inverse[raw_order[first_source]]] = source_views[raw_order[first_source]]
466
+ mask_by_voxel = np.zeros(len(unique_voxels), dtype=np.int32)
467
+ np.bitwise_or.at(mask_by_voxel, inverse, source_masks)
468
+ points = (grouped_points / np.maximum(grouped_weight[:, None], 1e-6)).astype(np.float32)
469
+ colors = np.clip(
470
+ grouped_colors / np.maximum(grouped_weight[:, None], 1e-6), 0.0, 255.0
471
+ ).astype(np.uint8)
472
+ weights = (grouped_weight / np.maximum(counts, 1.0)).astype(np.float32)
473
+ source_views = source_by_voxel
474
+ source_masks = mask_by_voxel
475
+ if len(points) > max_points:
476
+ keep = np.argsort(-weights, kind="stable")[:max_points]
477
+ points, colors, weights = points[keep], colors[keep], weights[keep]
478
+ source_views, source_masks = source_views[keep], source_masks[keep]
479
+ return FusionResult(points, colors, weights, source_views, source_masks)
480
+
481
+
482
+ def fusion_metrics(result: FusionResult) -> dict[str, float | int]:
483
+ if not len(result.points):
484
+ return {
485
+ "point_count": 0,
486
+ "confidence_mean": 0.0,
487
+ "confidence_p95": 0.0,
488
+ "dominant_source_view_count": 0,
489
+ "supported_source_view_count": 0,
490
+ "multi_view_voxel_fraction": 0.0,
491
+ }
492
+ supported_mask = int(np.bitwise_or.reduce(result.source_masks))
493
+ multi_view = np.fromiter(
494
+ (int(mask).bit_count() > 1 for mask in result.source_masks),
495
+ dtype=bool,
496
+ count=len(result.source_masks),
497
+ )
498
+ return {
499
+ "point_count": int(len(result.points)),
500
+ "confidence_mean": float(result.weights.mean()),
501
+ "confidence_p95": float(np.percentile(result.weights, 95)),
502
+ "dominant_source_view_count": int(len(np.unique(result.source_views))),
503
+ "supported_source_view_count": supported_mask.bit_count(),
504
+ "multi_view_voxel_fraction": float(multi_view.mean()),
505
+ }
506
+
507
+
508
+ def gaussian_initialization(weights: np.ndarray | None, point_count: int) -> tuple[np.ndarray, np.ndarray]:
509
+ """Map confidence weights to initial opacity and isotropic log-scales.
510
+
511
+ This is deliberately a lightweight initialization heuristic. It does not
512
+ claim to replace a learned Gaussian optimizer.
513
+ """
514
+ if weights is None or len(weights) != point_count:
515
+ normalized = np.ones(point_count, dtype=np.float32)
516
+ else:
517
+ normalized = np.clip(np.asarray(weights, dtype=np.float32), 0.0, 1.0)
518
+ opacity = 0.05 + 0.90 * normalized
519
+ log_scale = -4.605 + 0.8 * (1.0 - normalized)
520
+ return opacity, log_scale
521
+
522
+
523
+ def write_confidence_ply(
524
+ path: str | Path,
525
+ points: np.ndarray,
526
+ colors: np.ndarray,
527
+ confidence: np.ndarray,
528
+ source_views: np.ndarray | None = None,
529
+ source_masks: np.ndarray | None = None,
530
+ ) -> None:
531
+ """Write an ASCII PLY retaining confidence and optional source provenance."""
532
+ points = np.asarray(points, dtype=np.float32)
533
+ colors = np.asarray(colors, dtype=np.uint8)[..., :3]
534
+ confidence = np.asarray(confidence, dtype=np.float32)
535
+ if points.ndim != 2 or points.shape[1] != 3 or colors.shape != (len(points), 3):
536
+ raise ValueError("points and colors must contain matching Nx3 arrays")
537
+ if confidence.shape != (len(points),):
538
+ raise ValueError("confidence must contain one value per point")
539
+ if source_views is None:
540
+ source_views = np.full(len(points), -1, dtype=np.int32)
541
+ source_views = np.asarray(source_views, dtype=np.int32)
542
+ if source_views.shape != (len(points),):
543
+ raise ValueError("source_views must contain one value per point")
544
+ if source_masks is None:
545
+ source_masks = np.where(source_views >= 0, 1 << source_views, 0).astype(np.int32)
546
+ source_masks = np.asarray(source_masks, dtype=np.int32)
547
+ if source_masks.shape != (len(points),):
548
+ raise ValueError("source_masks must contain one value per point")
549
+ header = [
550
+ "ply", "format ascii 1.0", f"element vertex {len(points)}",
551
+ "property float x", "property float y", "property float z",
552
+ "property uchar red", "property uchar green", "property uchar blue",
553
+ "property float confidence", "property int source_view", "property int source_mask", "end_header",
554
+ ]
555
+ with Path(path).open("w", encoding="utf-8") as handle:
556
+ handle.write("\n".join(header) + "\n")
557
+ for point, color, score, source_view, source_mask in zip(points, colors, confidence, source_views, source_masks):
558
+ handle.write(
559
+ "{:.7g} {:.7g} {:.7g} {} {} {} {:.7g} {} {}\n".format(
560
+ *point, *color, float(score), int(source_view), int(source_mask)
561
+ )
562
+ )
563
+
564
+
565
+ def write_gaussian_ply(
566
+ path: str | Path,
567
+ points: np.ndarray,
568
+ colors: np.ndarray,
569
+ weights: np.ndarray | None = None,
570
+ source_views: np.ndarray | None = None,
571
+ source_masks: np.ndarray | None = None,
572
+ ) -> None:
573
+ """Write a confidence-initialized 3DGS PLY with evidence fields."""
574
+ points = np.asarray(points, dtype=np.float32)
575
+ colors = np.asarray(colors, dtype=np.uint8)[..., :3]
576
+ if points.ndim != 2 or points.shape[1] != 3 or colors.shape != (len(points), 3):
577
+ raise ValueError("points and colors must contain matching Nx3 arrays")
578
+ opacity, log_scale = gaussian_initialization(weights, len(points))
579
+ if weights is None or len(weights) != len(points):
580
+ exported_confidence = np.ones(len(points), dtype=np.float32)
581
+ else:
582
+ exported_confidence = np.clip(np.asarray(weights, dtype=np.float32), 0.0, 1.0)
583
+ if source_views is None or len(source_views) != len(points):
584
+ source_views = np.full(len(points), -1, dtype=np.int32)
585
+ else:
586
+ source_views = np.asarray(source_views, dtype=np.int32)
587
+ if source_masks is None:
588
+ source_masks = np.where(source_views >= 0, 1 << source_views, 0).astype(np.int32)
589
+ source_masks = np.asarray(source_masks, dtype=np.int32)
590
+ if source_masks.shape != (len(points),):
591
+ raise ValueError("source_masks must contain one value per point")
592
+ dc = (colors.astype(np.float32) / 255.0 - 0.5) / 0.2820947918
593
+ header = [
594
+ "ply", "format ascii 1.0", f"element vertex {len(points)}",
595
+ "property float x", "property float y", "property float z",
596
+ "property float nx", "property float ny", "property float nz",
597
+ "property float f_dc_0", "property float f_dc_1", "property float f_dc_2",
598
+ "property float opacity", "property float scale_0", "property float scale_1",
599
+ "property float scale_2", "property float rot_0", "property float rot_1",
600
+ "property float rot_2", "property float rot_3",
601
+ "property float confidence", "property int source_view", "property int source_mask", "end_header",
602
+ ]
603
+ with Path(path).open("w", encoding="utf-8") as handle:
604
+ handle.write("\n".join(header) + "\n")
605
+ for point, color, alpha, scale, score, source_view, source_mask in zip(
606
+ points, dc, opacity, log_scale, exported_confidence, source_views, source_masks
607
+ ):
608
+ handle.write(
609
+ "{:.7g} {:.7g} {:.7g} 0 0 0 {:.7g} {:.7g} {:.7g} {:.7g} {:.7g} {:.7g} {:.7g} 1 0 0 0 {:.7g} {} {}\n".format(
610
+ *point, *color, alpha, scale, scale, scale, float(score), int(source_view), int(source_mask)
611
+ )
612
+ )