""" bash: python vis_scene_occ.py --pkl ./Replica_OCC/global_occ_package/office0.pkl --downsample 1 """ import argparse import pickle import numpy as np import open3d as o3d def label_to_color(labels: np.ndarray) -> np.ndarray: """ Deterministic pseudo-color for semantic labels (>0). labels: (N,) returns: (N,3) in [0,1] """ labels = labels.astype(np.int64) r = ((labels * 37) % 255) / 255.0 g = ((labels * 17) % 255) / 255.0 b = ((labels * 97) % 255) / 255.0 return np.stack([r, g, b], axis=1).astype(np.float32) def _as_numpy(x): if isinstance(x, np.ndarray): return x return np.asarray(x) def resize_mask_to_labels_nn(mask_3d: np.ndarray, target_shape): """ Nearest-neighbor resize for 3D mask. mask_3d: (sx,sy,sz) target_shape: (tx,ty,tz) return: (tx,ty,tz) float32 """ src = _as_numpy(mask_3d) if src.ndim != 3: raise ValueError(f"resize_mask_to_labels_nn expects 3D, got {src.ndim}D shape={src.shape}") if tuple(src.shape) == tuple(target_shape): return src.astype(np.float32) sx, sy, sz = src.shape tx, ty, tz = target_shape # nearest-neighbor index mapping xs = np.round(np.linspace(0, sx - 1, tx)).astype(np.int64) ys = np.round(np.linspace(0, sy - 1, ty)).astype(np.int64) zs = np.round(np.linspace(0, sz - 1, tz)).astype(np.int64) out = src[np.ix_(xs, ys, zs)] return out.astype(np.float32) def detect_format(d: dict): """ Return mode: 'dense' or 'sparse' Also return extracted (pts, labels, mask) in some raw form. Accepts: Dense: global_pts: (Nx,Ny,Nz,3) global_labels: (Nx,Ny,Nz) or (Nx,Ny,Nz,1) global_mask: (Nx,Ny,Nz) OR other shape (will be resized) Sparse: global_pts: (N,3) global_labels: (N,) global_mask: (N,) """ if "global_pts" not in d: raise KeyError("pkl missing key: global_pts") pts = _as_numpy(d["global_pts"]) # labels key name could vary; try common ones if "global_labels" in d: labels = _as_numpy(d["global_labels"]) elif "labels" in d: labels = _as_numpy(d["labels"]) else: labels = None # mask key name could vary; try common ones if "global_mask" in d: mask = _as_numpy(d["global_mask"]) elif "mask" in d: mask = _as_numpy(d["mask"]) else: mask = None # Dense if pts is 4D (...,3) if pts.ndim == 4 and pts.shape[-1] == 3: return "dense", pts, labels, mask # Sparse if pts is 2D (N,3) if pts.ndim == 2 and pts.shape[1] == 3: return "sparse", pts, labels, mask # Fallback: try to interpret any (N,3) shaped last dim if pts.shape[-1] == 3: return "sparse", pts.reshape(-1, 3), labels, mask raise ValueError(f"Unrecognized global_pts shape: {pts.shape}") def coerce_dense_labels(labels: np.ndarray, target_shape): """ Make labels dense grid of shape target_shape (Nx,Ny,Nz). labels can be (Nx,Ny,Nz), (Nx,Ny,Nz,1), or flat (N,). """ if labels is None: return np.zeros(target_shape, dtype=np.int32) lab = _as_numpy(labels) if lab.ndim == 3 and tuple(lab.shape) == tuple(target_shape): return lab.astype(np.int32) if lab.ndim == 4 and lab.shape[-1] == 1 and tuple(lab.shape[:3]) == tuple(target_shape): return lab[..., 0].astype(np.int32) # flat if lab.ndim == 1: if lab.size == int(np.prod(target_shape)): return lab.reshape(target_shape).astype(np.int32) # last resort: try reshape if total matches if lab.size == int(np.prod(target_shape)): return lab.reshape(target_shape).astype(np.int32) print(f"[Warn] Cannot coerce labels to target shape. labels shape={lab.shape}, target={target_shape}. Use zeros.") return np.zeros(target_shape, dtype=np.int32) def coerce_dense_mask(mask: np.ndarray, target_shape, allow_resize=True): """ Make mask dense grid of shape target_shape (Nx,Ny,Nz). mask can be: - (Nx,Ny,Nz) - different 3D (will NN-resize if allow_resize) - flat (N,) """ if mask is None: return np.ones(target_shape, dtype=np.float32) m = _as_numpy(mask) # already matching if m.ndim == 3 and tuple(m.shape) == tuple(target_shape): return m.astype(np.float32) # different 3D -> resize if m.ndim == 3 and allow_resize: print(f"[Warn] mask shape {m.shape} != labels shape {target_shape}, resizing mask by NN") return resize_mask_to_labels_nn(m, target_shape) # flat -> reshape if possible if m.ndim == 1: if m.size == int(np.prod(target_shape)): return m.reshape(target_shape).astype(np.float32) # last resort: if sizes match, reshape anyway if m.size == int(np.prod(target_shape)): return m.reshape(target_shape).astype(np.float32) print(f"[Warn] Cannot coerce mask to target shape. mask shape={m.shape}, target={target_shape}. Use ones.") return np.ones(target_shape, dtype=np.float32) def coerce_sparse_labels(labels: np.ndarray, n_points: int): if labels is None: return np.zeros((n_points,), dtype=np.int32) lab = _as_numpy(labels).reshape(-1) if lab.size == n_points: return lab.astype(np.int32) print(f"[Warn] Sparse labels size mismatch: labels={lab.size}, pts={n_points}. Truncate/min-align.") n = min(lab.size, n_points) out = np.zeros((n_points,), dtype=np.int32) out[:n] = lab[:n].astype(np.int32) return out def coerce_sparse_mask(mask: np.ndarray, n_points: int): if mask is None: return np.ones((n_points,), dtype=np.float32) m = _as_numpy(mask).reshape(-1) if m.size == n_points: return m.astype(np.float32) print(f"[Warn] Sparse mask size mismatch: mask={m.size}, pts={n_points}. Truncate/min-align.") n = min(m.size, n_points) out = np.ones((n_points,), dtype=np.float32) out[:n] = m[:n].astype(np.float32) return out def main(): parser = argparse.ArgumentParser() parser.add_argument("--pkl", type=str, required=True, help="scene-level occ pkl") parser.add_argument("--downsample", type=int, default=1, help="visualization downsample stride (>=1), 1 = no downsample") args = parser.parse_args() with open(args.pkl, "rb") as f: d = pickle.load(f) mode, pts_raw, labels_raw, mask_raw = detect_format(d) # Print raw shapes try: print("[Info] global_pts shape:", _as_numpy(pts_raw).shape) except Exception: pass if labels_raw is not None: print("[Info] global_labels shape:", _as_numpy(labels_raw).shape) if mask_raw is not None: print("[Info] global_mask shape:", _as_numpy(mask_raw).shape) if mode == "dense": # pts: (Nx,Ny,Nz,3) pts_grid = _as_numpy(pts_raw).astype(np.float32) Nx, Ny, Nz = pts_grid.shape[:3] target_shape = (Nx, Ny, Nz) print("[Mode] Dense grid detected") print(f"[Info] scene_dim = {target_shape}") labels_grid = coerce_dense_labels(labels_raw, target_shape) mask_grid = coerce_dense_mask(mask_raw, target_shape, allow_resize=True) # flatten all aligned arrays pts = pts_grid.reshape(-1, 3) labels = labels_grid.reshape(-1) mask = mask_grid.reshape(-1) else: # sparse print("[Mode] Sparse points detected") pts = _as_numpy(pts_raw).reshape(-1, 3).astype(np.float32) labels = coerce_sparse_labels(labels_raw, pts.shape[0]) mask = coerce_sparse_mask(mask_raw, pts.shape[0]) print(f"[Info] points = {pts.shape[0]}") # optional downsample for speed (stride over flattened list) if args.downsample > 1 and pts.shape[0] > 0: sel = np.arange(0, pts.shape[0], args.downsample, dtype=np.int64) pts = pts[sel] labels = labels[sel] mask = mask[sel] # colors colors = np.zeros((pts.shape[0], 3), dtype=np.float32) # --- color rules --- # mask == 0 → dark gray mask0 = mask < 0.5 colors[mask0] = np.array([0.9, 0.9, 0.9], dtype=np.float32) # light gray # mask == 1 & label == 0 → light gray (empty but valid) mask1_empty = (mask >= 0.5) & (labels == 0) colors[mask1_empty] = np.array([0.2, 0.2, 0.2], dtype=np.float32) # dark gray # mask == 1 & label > 0 → semantic color mask1_sem = (mask >= 0.5) & (labels > 0) if np.any(mask1_sem): colors[mask1_sem] = label_to_color(labels[mask1_sem]) # build Open3D point cloud pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pts.astype(np.float32)) pcd.colors = o3d.utility.Vector3dVector(colors.astype(np.float32)) # stats print("[Stats]") print(" total points:", pts.shape[0]) print(" mask=1 ratio:", float((mask >= 0.5).mean()) if pts.shape[0] > 0 else 0.0) print(" semantic voxels:", int((labels > 0).sum())) o3d.visualization.draw_geometries( [pcd], window_name="Scene-level OCC (mask + semantic)", width=1280, height=960, ) if __name__ == "__main__": main()