junaid-simamdigital commited on
Commit
e539df0
·
verified ·
1 Parent(s): 1ab4bf3

Add tested depth and pose fusion bridge

Browse files
Files changed (1) hide show
  1. depth_bridge.py +108 -0
depth_bridge.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model-agnostic depth/pose bridge for the future Anything2GS backends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ def _intrinsics(intrinsics, width: int, height: int) -> np.ndarray:
9
+ if intrinsics is None:
10
+ return np.array([[width, 0.0, (width - 1) / 2], [0.0, height, (height - 1) / 2], [0.0, 0.0, 1.0]], dtype=np.float32)
11
+ matrix = np.asarray(intrinsics, dtype=np.float32)
12
+ if matrix.shape != (3, 3) or not np.isfinite(matrix).all():
13
+ raise ValueError("intrinsics must be a finite 3x3 matrix")
14
+ return matrix
15
+
16
+
17
+ def _pose(pose) -> np.ndarray:
18
+ if pose is None:
19
+ return np.eye(4, dtype=np.float32)
20
+ matrix = np.asarray(pose, dtype=np.float32)
21
+ if matrix.shape == (3, 4):
22
+ result = np.eye(4, dtype=np.float32)
23
+ result[:3] = matrix
24
+ matrix = result
25
+ if matrix.shape != (4, 4) or not np.isfinite(matrix).all():
26
+ raise ValueError("pose must be a finite 4x4 or 3x4 world-to-camera matrix")
27
+ return matrix
28
+
29
+
30
+ def depth_view_to_points(depth, colors, confidence=None, intrinsics=None, pose=None):
31
+ """Project one inverse-relative-depth view into world coordinates.
32
+
33
+ The convention matches Simam3D: larger normalized depth values are closer
34
+ to the camera. Poses are world-to-camera; the returned points are world
35
+ points. This function does not estimate depth or camera pose.
36
+ """
37
+ depth = np.asarray(depth, dtype=np.float32)
38
+ colors = np.asarray(colors, dtype=np.uint8)
39
+ if depth.ndim != 2 or colors.shape != (*depth.shape, 3):
40
+ raise ValueError("depth must be HxW and colors must be HxWx3")
41
+ height, width = depth.shape
42
+ confidence = np.ones_like(depth, dtype=np.float32) if confidence is None else np.asarray(confidence, dtype=np.float32)
43
+ if confidence.shape != depth.shape:
44
+ raise ValueError("confidence must match depth shape")
45
+ valid = np.isfinite(depth) & np.isfinite(confidence) & (confidence > 0)
46
+ if not valid.any():
47
+ return np.empty((0, 3), np.float32), np.empty((0, 3), np.uint8), np.empty((0,), np.float32)
48
+ safe_depth = np.nan_to_num(depth, nan=0.0, posinf=1.0, neginf=0.0)
49
+ minimum = float(safe_depth[valid].min())
50
+ z = 1.0 / np.maximum(safe_depth - minimum + 1e-3, 1e-3)
51
+ k = _intrinsics(intrinsics, width, height)
52
+ yy, xx = np.nonzero(valid)
53
+ camera = np.column_stack([
54
+ (xx - k[0, 2]) * z[yy, xx] / max(float(k[0, 0]), 1e-6),
55
+ (yy - k[1, 2]) * z[yy, xx] / max(float(k[1, 1]), 1e-6),
56
+ z[yy, xx],
57
+ ]).astype(np.float32)
58
+ world_to_camera = _pose(pose)
59
+ camera_to_world = np.linalg.inv(world_to_camera)
60
+ homogeneous = np.column_stack([camera, np.ones(len(camera), dtype=np.float32)])
61
+ points = (homogeneous @ camera_to_world.T)[:, :3].astype(np.float32)
62
+ return points, colors[yy, xx], confidence[yy, xx].astype(np.float32)
63
+
64
+
65
+ def fuse_depth_views(views, voxel_size: float = 0.02, max_points: int = 150_000) -> dict[str, np.ndarray]:
66
+ """Fuse projected views by confidence-weighted voxel centroid and color."""
67
+ if voxel_size <= 0 or max_points < 1:
68
+ raise ValueError("voxel_size and max_points must be positive")
69
+ all_points, all_colors, all_weights, all_sources = [], [], [], []
70
+ for source, view in enumerate(views):
71
+ points, colors, weights = depth_view_to_points(**view)
72
+ all_points.append(points)
73
+ all_colors.append(colors)
74
+ all_weights.append(weights)
75
+ all_sources.append(np.full(len(points), source, dtype=np.int32))
76
+ if not all_points or not any(len(points) for points in all_points):
77
+ return {"points": np.empty((0, 3), np.float32), "colors": np.empty((0, 3), np.uint8), "confidence": np.empty((0,), np.float32), "source_views": np.empty((0,), np.int32), "source_masks": np.empty((0,), np.int32)}
78
+ points = np.concatenate(all_points)
79
+ colors = np.concatenate(all_colors)
80
+ weights = np.concatenate(all_weights)
81
+ sources = np.concatenate(all_sources)
82
+ keys = np.floor(points / voxel_size).astype(np.int64)
83
+ order = np.lexsort((keys[:, 2], keys[:, 1], keys[:, 0]))
84
+ keys, points, colors, weights, sources = keys[order], points[order], colors[order], weights[order], sources[order]
85
+ unique, starts = np.unique(keys, axis=0, return_index=True)
86
+ ends = np.r_[starts[1:], len(keys)]
87
+ fused_points, fused_colors, fused_weights, fused_sources, masks = [], [], [], [], []
88
+ for start, end in zip(starts, ends):
89
+ local = weights[start:end]
90
+ total = float(local.sum())
91
+ fused_points.append((points[start:end] * local[:, None]).sum(axis=0) / max(total, 1e-8))
92
+ fused_colors.append(np.clip(np.rint((colors[start:end] * local[:, None]).sum(axis=0) / max(total, 1e-8)), 0, 255))
93
+ fused_weights.append(total / (end - start))
94
+ strongest = start + int(np.argmax(local))
95
+ fused_sources.append(sources[strongest])
96
+ mask = 0
97
+ for source in np.unique(sources[start:end]):
98
+ if 0 <= source < 30:
99
+ mask |= 1 << int(source)
100
+ masks.append(mask)
101
+ keep = np.argsort(-np.asarray(fused_weights))[:max_points]
102
+ return {
103
+ "points": np.asarray(fused_points, np.float32)[keep],
104
+ "colors": np.asarray(fused_colors, np.uint8)[keep],
105
+ "confidence": np.asarray(fused_weights, np.float32)[keep],
106
+ "source_views": np.asarray(fused_sources, np.int32)[keep],
107
+ "source_masks": np.asarray(masks, np.int32)[keep],
108
+ }