-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathscene_utils.py
More file actions
577 lines (485 loc) · 22.1 KB
/
Copy pathscene_utils.py
File metadata and controls
577 lines (485 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
import os
from copy import deepcopy
from typing import List, Tuple
import open3d as o3d
import numpy as np
import cv2
from PIL import Image
import torch
import trimesh
from itertools import product
import math
from skimage.draw import line_nd
from sklearn.decomposition import PCA
from trellis.representations.mesh import MeshExtractResult
from scipy.ndimage import zoom
from scipy.ndimage import generic_filter
def filter_depth_discontinuities(depth_map, threshold=0.1, kernel_size=5, edge_dilation=2):
"""
Filter out depth values near discontinuities (object edges) to remove flying pixels.
Args:
depth_map (np.ndarray): Depth map of shape (H, W) or (H, W, 1)
threshold (float): Relative depth difference threshold (as fraction of local depth).
E.g., 0.1 means 10% depth change is considered a discontinuity.
kernel_size (int): Size of the local window for detecting discontinuities (must be odd).
edge_dilation (int): Number of pixels to dilate the edge mask (removes more around edges).
Returns:
mask (np.ndarray): Boolean mask (H, W), True for valid pixels, False for edge pixels.
"""
# Handle (H, W, 1) format
if depth_map.ndim == 3 and depth_map.shape[2] == 1:
depth_map = depth_map[..., 0]
H, W = depth_map.shape
# 1. Compute depth gradients (Sobel)
grad_x = cv2.Sobel(depth_map, cv2.CV_64F, 1, 0, ksize=3)
grad_y = cv2.Sobel(depth_map, cv2.CV_64F, 0, 1, ksize=3)
grad_magnitude = np.sqrt(grad_x**2 + grad_y**2)
# 2. Normalize gradient by local depth (relative change)
# Avoid division by zero
depth_safe = np.maximum(depth_map, 1e-6)
relative_grad = grad_magnitude / depth_safe
# 3. Detect discontinuities
discontinuity_mask = relative_grad > threshold
# 4. Dilate the mask to remove more pixels around edges
if edge_dilation > 0:
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (edge_dilation*2+1, edge_dilation*2+1))
discontinuity_mask = cv2.dilate(discontinuity_mask.astype(np.uint8), kernel, iterations=1).astype(bool)
# 5. Additionally filter by local variance (high variance = edge)
def local_std(values):
return np.std(values)
local_variance = generic_filter(depth_map, local_std, size=kernel_size, mode='constant', cval=0)
variance_mask = local_variance > (threshold * depth_safe)
# Combine masks
edge_mask = discontinuity_mask | variance_mask
valid_mask = ~edge_mask
return valid_mask
def align_point_cloud(pcd, horizontal_axis=None, relative_threshold=0.01, camera_forward=None):
"""Align point cloud so the ground plane normal aligns with z-axis.
Args:
pcd (o3d.geometry.PointCloud): point cloud to align.
horizontal_axis (str): Which horizontal axis the longest direction should
face. Accepts "x", "-x", "y", "-y" ("+x"/"+y" also allowed).
If None, will use bounding box-based alignment.
camera_forward (array-like): Camera forward direction vector [x, y, z].
If provided, will align this direction (projected to XY plane) with horizontal_axis.
Takes priority over bounding box alignment.
"""
print('Aligning point cloud to horizontal plane...')
bbox = pcd.get_axis_aligned_bounding_box()
extent = bbox.get_extent()
max_extent = np.max(extent)
distance_threshold = max_extent * relative_threshold
plane_model, inliers = pcd.segment_plane(
distance_threshold=distance_threshold,
ransac_n=3,
num_iterations=1000
)
[a, b, c, d] = plane_model
print(f"Plane equation: {a:.3f}x + {b:.3f}y + {c:.3f}z + {d:.3f} = 0")
print(f"Inliers: {len(inliers)} / {len(pcd.points)} ({len(inliers)/len(pcd.points)*100:.1f}%)")
# Rotate cloud so plane normal aligns with (0,0,-1)
normal_current = np.array([a, b, c], dtype=np.float64)
normal_current /= np.linalg.norm(normal_current)
normal_target = np.array([0, 0, -1], dtype=np.float64) # Target -z direction
print(f"Current normal: [{normal_current[0]:.4f}, {normal_current[1]:.4f}, {normal_current[2]:.4f}]")
print(f"Dot product with -z-axis: {np.dot(normal_current, normal_target):.4f}")
v = np.cross(normal_current, normal_target)
s = np.linalg.norm(v)
c_ = np.dot(normal_current, normal_target)
if s < 1e-10:
R = np.eye(3)
print("Normal already aligned with -z-axis (no rotation needed)")
else:
vx = np.array([
[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v[1], v[0], 0 ]
])
R = np.eye(3) + vx + vx @ vx * ((1 - c_) / (s**2))
# Compute rotation angle for debugging
angle_rad = np.arccos(np.clip(c_, -1.0, 1.0))
angle_deg = np.degrees(angle_rad)
print(f"Rotation angle: {angle_deg:.2f}° around axis [{v[0]/s:.4f}, {v[1]/s:.4f}, {v[2]/s:.4f}]")
transform = np.block([
[R, np.zeros((3,1))],
[np.zeros((1,3)), np.ones((1,1))]
])
# Verify final transformation
test_normal = (transform[:3, :3] @ normal_current)
print(f"Final normal after rotation: [{test_normal[0]:.4f}, {test_normal[1]:.4f}, {test_normal[2]:.4f}]")
# Align camera forward direction or bounding box longest axis with target axis
if horizontal_axis is not None:
points = np.asarray(pcd.points)
if points.size:
# Apply current transformation to get aligned points
rot_initial = transform[:3, :3]
# Parse target axis
axis = horizontal_axis.lower()
axis_map = {
"x": 0.0,
"+x": 0.0,
"-x": np.pi,
"y": np.pi / 2,
"+y": np.pi / 2,
"-y": -np.pi / 2,
}
if axis not in axis_map:
raise ValueError("horizontal_axis must be one of {'x', '+x', '-x', 'y', '+y', '-y'}")
desired_angle = axis_map[axis]
# Determine current angle based on camera forward or bounding box
if camera_forward is not None:
# Use camera forward direction
cam_fwd = np.array(camera_forward, dtype=np.float64)
cam_fwd = cam_fwd / np.linalg.norm(cam_fwd)
# Transform camera forward to aligned space
aligned_fwd = rot_initial @ cam_fwd
# Project to XY plane
fwd_xy = aligned_fwd[:2]
fwd_xy_norm = np.linalg.norm(fwd_xy)
if fwd_xy_norm > 1e-6:
fwd_xy = fwd_xy / fwd_xy_norm
# Current angle of camera forward in XY plane
current_angle = np.arctan2(fwd_xy[1], fwd_xy[0])
print(f"Camera forward direction in XY plane: [{fwd_xy[0]:.4f}, {fwd_xy[1]:.4f}]")
print(f"Camera forward angle: {np.degrees(current_angle):.2f}°")
else:
print("Warning: Camera forward is vertical, falling back to bounding box")
camera_forward = None # Fall back to bounding box
if camera_forward is None:
# Use bounding box longest axis
aligned_pts = points @ rot_initial.T
xy = aligned_pts[:, :2]
valid = np.all(np.isfinite(xy), axis=1)
xy = xy[valid]
if xy.size:
# Compute bounding box in XY plane
min_xy = xy.min(axis=0)
max_xy = xy.max(axis=0)
extents = max_xy - min_xy # [x_extent, y_extent]
print(f"Aligned bounding box XY extents: X={extents[0]:.2f}, Y={extents[1]:.2f}")
# Determine which axis is longer
if extents[0] > extents[1]:
current_angle = 0.0 # longest axis along +X
print("Longest axis is currently along X")
else:
current_angle = np.pi / 2 # longest axis along +Y
print("Longest axis is currently along Y")
else:
print("Warning: No valid points for alignment")
return transform
# Calculate rotation needed
delta = current_angle - desired_angle
# Normalize angle to [-pi, pi]
delta = np.arctan2(np.sin(delta), np.cos(delta))
if abs(delta) > 1e-6:
cos_a, sin_a = np.cos(-delta), np.sin(-delta)
rot_z = np.array([
[cos_a, -sin_a, 0, 0],
[sin_a, cos_a, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
])
transform = rot_z @ transform
print(f"Rotating {np.degrees(delta):.2f}° around Z to align with {axis}")
else:
print("No rotation needed - already aligned")
return transform
def carve_voxel_grid(point_map,
resolution_xyz,
camera_origin,
scale=0.5,
min_bound=(-0.5, -0.5, -0.5),
max_bound=(0.5, 0.5, 0.5)):
"""
Voxel-carve a 3-state grid from a depth point_map:
0 = unknown (never seen),
1 = free (visible empty),
2 = occupied(surface)
Parameters
----------
point_map : (H, W, 3) array of XYZ points
resolution_xyz : (3,) ints, number of voxels in x,y,z
extrinsic : (3,4) camera extrinsic matrix
min_bound, max_bound : world-space grid bounds
Returns
-------
grid : (res_x, res_y, res_z) uint8 array
{0:unknown, 1:free, 2:occupied}
"""
camera_origin = camera_origin * scale # scale to voxel space
# H, W, _ = point_map.shape
res = np.array(resolution_xyz, int)
min_b = np.array(min_bound, float)
max_b = np.array(max_bound, float)
voxel_size = (max_b - min_b) / res
grid = np.zeros(res, dtype=np.uint8)
cam_idx = ((camera_origin - min_b) / voxel_size).astype(int)
cam_idx = np.clip(cam_idx, 0, res - 1)
pts = point_map.reshape(-1, 3)
surf_idx = ((pts - min_b) / voxel_size).astype(int)
valid = np.all((surf_idx >= 0) & (surf_idx < res), axis=1)
surf_idx = surf_idx[valid]
for idx in surf_idx:
xs, ys, zs = line_nd(cam_idx, idx, endpoint=True)
if len(xs) == 0:
continue
# mark free (all but the last)
grid[xs[:-1], ys[:-1], zs[:-1]] = 1
# mark occupied (the last voxel on the ray)
grid[xs[-1], ys[-1], zs[-1]] = 2
return grid
def save_voxel_grid_as_ply(output_path, binary_voxel, resolution_xyz, min_bound=(-0.5, -0.5, -0.5), max_bound=(0.5, 0.5, 0.5),
voxel_feature=None):
"""
Convert a binary voxel grid to point cloud and save as a .ply file.
Parameters:
-----------
binary_voxel : np.ndarray
A (res_x, res_y, res_z) boolean array of voxel occupancy.
resolution_xyz : tuple of int
Resolution of the voxel grid in (x, y, z).
min_bound : tuple of float
Minimum bounds of the voxel grid (x_min, y_min, z_min).
max_bound : tuple of float
Maximum bounds of the voxel grid (x_max, y_max, z_max).
output_path : str
Path to save the .ply point cloud.
"""
# Get occupied voxel indices
occupied_indices = np.argwhere(binary_voxel) # shape (N, 3)
if occupied_indices.shape[0] == 0:
print("No occupied voxels to save.")
return
# Compute voxel size and center offsets
min_bound = np.array(min_bound, dtype=np.float32)
max_bound = np.array(max_bound, dtype=np.float32)
resolution_xyz = np.array(resolution_xyz)
voxel_size = (max_bound - min_bound) / resolution_xyz
voxel_centers = occupied_indices * voxel_size + (voxel_size / 2.0) + min_bound
if voxel_feature is not None:
pca3 = PCA(n_components=3)
features = voxel_feature[occupied_indices[:, 0], occupied_indices[:, 1], occupied_indices[:, 2]]
feat3 = pca3.fit_transform(features)
min_ = feat3.min(axis=0)
max_ = feat3.max(axis=0)
colors = (feat3 - min_) / (max_ - min_)
else:
# random color
colors = np.random.rand(len(voxel_centers), 3)
# Convert to Open3D point cloud and save
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(voxel_centers)
pcd.colors = o3d.utility.Vector3dVector(colors) # orange
o3d.io.write_point_cloud(output_path, pcd)
print(f"Saved voxel centers to {output_path}")
def point_map_to_mask(point_map,
voxel_mask,
min_bound=(-0.5, -0.5, -0.5),
max_bound=(0.5, 0.5, 0.5),
point_valid_mask=None):
"""
Map a 3D-voxel boolean mask back onto a 2D point_map.
Parameters
----------
point_map : np.ndarray, shape (W, H, 3)
The per-pixel XYZ coordinates.
voxel_mask : np.ndarray, shape (res_x, res_y, res_z)
Boolean mask in voxel-space.
min_bound, max_bound : length-3 tuples
The same bounds you used to build your voxels.
Returns
-------
pixel_mask : np.ndarray, shape (W, H), dtype=bool
True where the corresponding point falls in a True voxel.
"""
W, H, _ = point_map.shape
pts = point_map.reshape(-1, 3) # (W*H, 3)
# derive resolution and voxel size
res = np.array(voxel_mask.shape, dtype=int) # (3,)
min_b = np.array(min_bound, dtype=float)
max_b = np.array(max_bound, dtype=float)
voxel_size = (max_b - min_b) / res # (3,)
# compute integer voxel indices
idx = ((pts - min_b) / voxel_size).astype(int) # (W*H, 3)
# mask out out-of-bound points
valid = np.all((idx >= 0) & (idx < res), axis=1) # (W*H,)
if point_valid_mask is not None:
point_valid_mask = point_valid_mask.reshape(-1).astype(bool)
valid = np.logical_and(valid, point_valid_mask)
pixel_mask_flat = np.zeros(W*H, dtype=bool)
# lookup masked voxels for valid points
valid_idx = idx[valid]
pixel_mask_flat[valid] = voxel_mask[
valid_idx[:, 0],
valid_idx[:, 1],
valid_idx[:, 2]
]
# reshape back to image
return pixel_mask_flat.reshape(W, H)
def patchify_balanced_seams(
binary_voxel: np.ndarray,
patch_shape: tuple[int,int,int],
overlap_ratio: float = 0.5,
) -> tuple[list[tuple[int,int,int]], list[np.ndarray]]:
"""
Generate patches with controllable overlap using balanced seam placement.
Creates a two-stage patching strategy that guarantees complete coverage:
1. Base grid with configurable stride (controlled by overlap_ratio)
2. Seam patches intelligently placed to fill any gaps between base patches
The algorithm ensures complete coverage by:
- Detecting gaps between adjacent base patches (when stride > overlap)
- Placing seam patches at balanced midpoints when a single seam suffices
- Adding multiple seams when gaps are too large for single-patch coverage
- The last base patch always extends to cover the boundary
Args:
binary_voxel: Boolean occupancy volume to cover.
patch_shape: Fixed patch dimensions (e.g. (64, 64, 64)).
overlap_ratio: Ratio of overlap between patches (0.0 to 1.0).
- 0.0: no overlap, minimal patches (stride = patch_size)
- 0.5: half overlap (stride = patch_size / 2, default)
- 0.75: high overlap (stride = patch_size / 4)
Higher values = more patches but smoother blending.
Returns:
starts: List of (x, y, z) anchors inside the original grid.
patches: List of boolean arrays copied from the input volume.
Complete coverage is guaranteed for the occupied region.
"""
# Validate overlap_ratio
if not 0.0 <= overlap_ratio < 1.0:
raise ValueError("overlap_ratio must be in range [0.0, 1.0)")
occupied = np.argwhere(binary_voxel)
if occupied.size == 0:
return [], []
min_v = occupied.min(axis=0)
max_v = occupied.max(axis=0)
spans = max_v - min_v + 1
px, py, pz = patch_shape
# Calculate stride based on overlap_ratio
# overlap_ratio = 0.5 means stride = patch_size * (1 - 0.5) = patch_size / 2
stride_x = max(1, int(round(px * (1 - overlap_ratio))))
stride_y = max(1, int(round(py * (1 - overlap_ratio))))
def axis_starts(span, size, stride):
starts = list(range(0, max(span - size + 1, 1), stride))
end = max(span - size, 0)
if starts[-1] != end:
starts.append(end)
return starts
# Z axis (no overlap in Z direction, centered)
def compute_centered_z_starts(span_z, size_z):
if span_z <= size_z:
# Single patch: center it on the occupied region
offset = (size_z - span_z) // 2
return [-offset]
else:
# Multiple patches: distribute evenly as before
num_patches = math.ceil(span_z / size_z)
return [int(round(i * (span_z - size_z) / (num_patches - 1)))
for i in range(num_patches)]
rel_z = compute_centered_z_starts(spans[2], pz)
# Step 1: Base grid with configurable stride
rel_x_base = axis_starts(spans[0], px, stride_x)
rel_y_base = axis_starts(spans[1], py, stride_y)
starts_base = {
(int(min_v[0] + rx), int(min_v[1] + ry), int(min_v[2] + rz))
for rx, ry, rz in product(rel_x_base, rel_y_base, rel_z)
}
# Step 2: Seam patches to fill gaps between base patches
starts_seam = set()
# X direction seams: check for gaps between adjacent base patches
for i in range(len(rel_x_base) - 1):
# Check if there's an uncovered gap between patches
# patch_i covers [rel_x_base[i], rel_x_base[i] + px)
# patch_i+1 covers [rel_x_base[i+1], rel_x_base[i+1] + px)
patch_i_end = rel_x_base[i] + px
patch_i1_start = rel_x_base[i+1]
if patch_i_end < patch_i1_start:
# There's a gap: [patch_i_end, patch_i1_start)
gap_size = patch_i1_start - patch_i_end
# Place seam at midpoint for balanced overlap
seam_rx = (rel_x_base[i] + rel_x_base[i+1]) // 2
# Ensure seam patch can cover the gap
seam_start = seam_rx
seam_end = seam_rx + px
# Verify coverage: seam should overlap with both adjacent patches
# and cover the entire gap
if seam_start <= patch_i_end and seam_end >= patch_i1_start:
for ry, rz in product(rel_y_base, rel_z):
starts_seam.add((
int(min_v[0] + seam_rx),
int(min_v[1] + ry),
int(min_v[2] + rz)
))
else:
# Midpoint doesn't work, need multiple seams
# Fill with patches at stride intervals within the gap
num_seams_needed = math.ceil(gap_size / stride_x)
for k in range(num_seams_needed):
seam_rx = patch_i_end + k * stride_x - (stride_x // 2)
seam_rx = max(rel_x_base[i], min(seam_rx, rel_x_base[i+1]))
for ry, rz in product(rel_y_base, rel_z):
starts_seam.add((
int(min_v[0] + seam_rx),
int(min_v[1] + ry),
int(min_v[2] + rz)
))
# Y direction seams: check for gaps between adjacent base patches
for j in range(len(rel_y_base) - 1):
patch_j_end = rel_y_base[j] + py
patch_j1_start = rel_y_base[j+1]
if patch_j_end < patch_j1_start:
# There's a gap
gap_size = patch_j1_start - patch_j_end
seam_ry = (rel_y_base[j] + rel_y_base[j+1]) // 2
seam_start = seam_ry
seam_end = seam_ry + py
if seam_start <= patch_j_end and seam_end >= patch_j1_start:
for rx, rz in product(rel_x_base, rel_z):
starts_seam.add((
int(min_v[0] + rx),
int(min_v[1] + seam_ry),
int(min_v[2] + rz)
))
else:
# Multiple seams needed
num_seams_needed = math.ceil(gap_size / stride_y)
for k in range(num_seams_needed):
seam_ry = patch_j_end + k * stride_y - (stride_y // 2)
seam_ry = max(rel_y_base[j], min(seam_ry, rel_y_base[j+1]))
for rx, rz in product(rel_x_base, rel_z):
starts_seam.add((
int(min_v[0] + rx),
int(min_v[1] + seam_ry),
int(min_v[2] + rz)
))
# Merge, deduplicate, and sort
starts = sorted(starts_base | starts_seam, key=lambda xyz: (xyz[1], xyz[0], xyz[2]))
# Extract all patches
patches = [
binary_voxel[x : x+px, y : y+py, z : z+pz].copy()
for x, y, z in starts
]
return starts, patches
def transform_mesh(mesh: MeshExtractResult, transform: np.ndarray):
if transform is None:
return mesh
T = torch.from_numpy(transform).float().to(mesh.vertices.device)
V = mesh.vertices @ T[:3, :3].T + T[:3, 3]
return MeshExtractResult(V, mesh.faces, mesh.vertex_attrs, res=mesh.res)
def concat_two(mesh1: MeshExtractResult, mesh2: MeshExtractResult) -> MeshExtractResult:
"""Concatenate two already‐transformed meshes (no extra transforms here)."""
v1, v2 = mesh1.vertices, mesh2.vertices
f1, f2 = mesh1.faces, mesh2.faces + v1.shape[0]
V = torch.cat([v1, v2], dim=0)
F = torch.cat([f1, f2], dim=0)
if mesh1.vertex_attrs is not None and mesh2.vertex_attrs is not None:
A = torch.cat([mesh1.vertex_attrs, mesh2.vertex_attrs], dim=0)
else:
A = None
return MeshExtractResult(V, F, A, res=mesh1.res)
def transform_gaussian(g, transform):
if transform is None:
return g
T = torch.from_numpy(transform).float().to(g._xyz.device)
g = deepcopy(g)
g._xyz = g._xyz @ T[:3, :3].T + T[:3, 3]
return g