| """ |
| bash: |
| |
| python prepare_scene_occ.py \ |
| --replica_root ./Replica_SLAM \ |
| --preprocessed_dir ./Replica_OCC/preprocessed \ |
| --out_dir ./Replica_OCC/global_occ_package \ |
| --scenes office0 \ |
| --obs_stride_frame 1 \ |
| --obs_stride_pix 1 \ |
| --mask_dilate 0 \ |
| --obs_max_frames -1 \ |
| --max_depth 10.0 |
| """ |
|
|
| import os |
| import json |
| import argparse |
| import pickle |
| import numpy as np |
| from PIL import Image |
| from tqdm import tqdm |
| from sklearn.neighbors import KDTree |
|
|
| try: |
| from scipy.ndimage import binary_dilation |
| HAS_SCIPY = True |
| except Exception: |
| HAS_SCIPY = False |
|
|
|
|
| def load_cam_params(replica_root: str): |
| cam_json = os.path.join(replica_root, "cam_params.json") |
| with open(cam_json, "r") as f: |
| js = json.load(f) |
| cam = js.get("camera", js) |
| fx, fy, cx, cy = float(cam["fx"]), float(cam["fy"]), float(cam["cx"]), float(cam["cy"]) |
| w, h = int(cam["w"]), int(cam["h"]) |
| scale = float(cam["scale"]) |
| K = np.eye(3, dtype=np.float32) |
| K[0, 0] = fx |
| K[1, 1] = fy |
| K[0, 2] = cx |
| K[1, 2] = cy |
| return K, (w, h), scale |
|
|
|
|
| def load_traj(traj_path: str): |
| traj = np.loadtxt(traj_path) |
| assert traj.ndim == 2 and traj.shape[1] == 16 |
| Ts = traj.reshape(-1, 4, 4).astype(np.float32) |
| return Ts |
|
|
|
|
| def load_preprocessed_scene(preprocessed_path: str): |
| """ |
| Expect either (N,4) [x,y,z,label] or (N,7) [x,y,z,r,g,b,label]. |
| Return xyz (N,3), label (N,) |
| """ |
| v = np.load(preprocessed_path) |
| if v.ndim != 2 or v.shape[1] not in (4, 7): |
| raise ValueError(f"Unexpected preprocessed shape: {v.shape}, path={preprocessed_path}") |
|
|
| if v.shape[1] == 4: |
| xyz = v[:, :3].astype(np.float32) |
| lab = v[:, 3].astype(np.int32) |
| else: |
| xyz = v[:, :3].astype(np.float32) |
| lab = v[:, 6].astype(np.int32) |
| return xyz, lab |
|
|
|
|
| def build_regular_grid(xyz_shifted, voxel_size=0.08): |
| """xyz_shifted already has min at ~0. Return grid_pts (Nx,Ny,Nz,3) and dims.""" |
| xyz_min = xyz_shifted.min(axis=0) |
| xyz_max = xyz_shifted.max(axis=0) |
|
|
| |
| xyz_min = np.floor(xyz_min / voxel_size) * voxel_size |
| xyz_max = np.ceil(xyz_max / voxel_size) * voxel_size |
|
|
| xs = np.arange(xyz_min[0], xyz_max[0] + 1e-9, voxel_size, dtype=np.float32) |
| ys = np.arange(xyz_min[1], xyz_max[1] + 1e-9, voxel_size, dtype=np.float32) |
| zs = np.arange(xyz_min[2], xyz_max[2] + 1e-9, voxel_size, dtype=np.float32) |
|
|
| gx, gy, gz = np.meshgrid(xs, ys, zs, indexing="ij") |
| grid_pts = np.stack([gx, gy, gz], axis=-1) |
| dims = [grid_pts.shape[0], grid_pts.shape[1], grid_pts.shape[2]] |
| return grid_pts, dims |
|
|
|
|
| def assign_labels_to_grid(grid_pts, xyz, lab, voxel_size=0.08): |
| """Nearest neighbor label assignment from sparse voxels to regular grid centers.""" |
| flat = grid_pts.reshape(-1, 3) |
| tree = KDTree(xyz, leaf_size=32) |
| dist, ind = tree.query(flat, k=1) |
| dist = dist.reshape(-1) |
| ind = ind.reshape(-1) |
|
|
| out = np.zeros((flat.shape[0],), dtype=np.int32) |
| m = dist <= voxel_size |
| out[m] = lab[ind[m]] |
| return out.reshape(grid_pts.shape[:3]) |
|
|
|
|
| def build_scene_mask_by_fused_frustums( |
| replica_root, |
| scene, |
| grid_pts, |
| Ts_cw, |
| K, |
| depth_scale, |
| max_frames=-1, |
| stride_frame=5, |
| obs_stride_pix=1, |
| max_depth=10.0, |
| tau=0.08, |
| ): |
| """Scene-level mask via per-frame frustum + depth test (union across frames). |
| |
| grid_pts is already in the Replica world coordinate system after adding origin_shift back. |
| No extra translation is applied inside this function, keeping it consistent with camera poses. |
| """ |
| scene_dir = os.path.join(replica_root, scene) |
| depth_dir = os.path.join(scene_dir, "depths") |
| if not os.path.isdir(depth_dir): |
| return np.zeros(grid_pts.shape[:3], dtype=np.float32), [] |
|
|
| depth_files = sorted([f for f in os.listdir(depth_dir) if f.endswith(".png")]) |
| if max_frames > 0: |
| depth_files = depth_files[:max_frames] |
|
|
| Nx, Ny, Nz = grid_pts.shape[:3] |
| mask = np.zeros((Nx, Ny, Nz), dtype=np.uint8) |
| used_imgs = [] |
|
|
| |
| Pw = grid_pts.reshape(-1, 3).astype(np.float32) |
|
|
| fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2] |
|
|
| it = enumerate(depth_files) |
| it = tqdm(list(it), desc=f"[mask] {scene}", leave=False) if len(depth_files) > 50 else it |
|
|
| for _, fname in it: |
| |
| |
| idx = int(fname.replace("depth", "").replace(".png", "")) |
| if (idx % stride_frame) != 0: |
| continue |
| if idx >= Ts_cw.shape[0]: |
| continue |
|
|
| depth_png = os.path.join(depth_dir, fname) |
| d16 = np.array(Image.open(depth_png).convert("I;16"), dtype=np.float32) |
| depth_m = d16 / float(depth_scale) |
| depth_m[depth_m > max_depth] = 0.0 |
| H, W = depth_m.shape |
|
|
| |
| Twc = Ts_cw[idx] |
| Rwc = Twc[:3, :3] |
| twc = Twc[:3, 3] |
|
|
| |
| Rcw = Rwc.T |
| Pc = (Rcw @ (Pw - twc[None, :]).T).T |
|
|
| z_all = Pc[:, 2] |
|
|
| |
| finite = np.isfinite(Pc).all(axis=1) & np.isfinite(z_all) |
| in_front = z_all > 1e-6 |
| ok = finite & in_front |
| if not np.any(ok): |
| continue |
|
|
| idx_ok = np.nonzero(ok)[0] |
| Pc_ok = Pc[idx_ok] |
|
|
| x = Pc_ok[:, 0] |
| y = Pc_ok[:, 1] |
| z = Pc_ok[:, 2] |
|
|
| |
| u = fx * (x / z) + cx |
| v = fy * (y / z) + cy |
|
|
| |
| uv_ok = np.isfinite(u) & np.isfinite(v) |
| if not np.any(uv_ok): |
| continue |
|
|
| idx_uv = idx_ok[uv_ok] |
| u = u[uv_ok] |
| v = v[uv_ok] |
| z = z[uv_ok] |
|
|
| ui = np.rint(u).astype(np.int32) |
| vi = np.rint(v).astype(np.int32) |
|
|
| |
| in_img = (ui >= 0) & (ui < W) & (vi >= 0) & (vi < H) |
| if not np.any(in_img): |
| continue |
|
|
| idx_img = idx_uv[in_img] |
| ui = ui[in_img] |
| vi = vi[in_img] |
| z = z[in_img] |
|
|
| |
| di = depth_m[vi, ui] |
| good_depth = di > 1e-6 |
| if not np.any(good_depth): |
| continue |
|
|
| idx_depth = idx_img[good_depth] |
| zi = z[good_depth] |
| di = di[good_depth] |
|
|
| valid = zi <= (di + tau) |
| idxs = idx_depth[valid] |
|
|
| if idxs.size > 0: |
| m = np.zeros((Pw.shape[0],), dtype=np.uint8) |
| m[idxs] = 1 |
| mask |= m.reshape(Nx, Ny, Nz) |
|
|
| rgb_path = os.path.join(scene_dir, "frames", f"frame{idx:06d}.jpg") |
| used_imgs.append(rgb_path) |
|
|
| return mask.astype(np.float32), used_imgs |
|
|
|
|
| def optional_mask_dilation(mask, dilate_iter=0): |
| if dilate_iter <= 0: |
| return mask |
| if not HAS_SCIPY: |
| print("[Warn] scipy not installed; skip dilation.") |
| return mask |
| return binary_dilation(mask.astype(np.uint8), iterations=dilate_iter).astype(np.float32) |
|
|
|
|
| def process_one_scene( |
| replica_root, |
| out_root, |
| scene, |
| preprocessed_dir, |
| voxel_size=0.08, |
| max_depth=10.0, |
| obs_max_frames=-1, |
| obs_stride_frame=5, |
| obs_stride_pix=1, |
| mask_dilate=0, |
| ): |
| pre_path = os.path.join(preprocessed_dir, f"{scene}.npy") |
| xyz, lab = load_preprocessed_scene(pre_path) |
|
|
| |
| origin_shift = xyz.min(axis=0) |
| xyz_shifted = xyz - origin_shift[None, :] |
|
|
| |
| grid_pts_shifted, dims = build_regular_grid(xyz_shifted, voxel_size=voxel_size) |
|
|
| |
| global_labels = assign_labels_to_grid(grid_pts_shifted, xyz_shifted, lab, voxel_size=voxel_size) |
|
|
| |
| grid_pts_world = grid_pts_shifted + origin_shift[None, None, None, :] |
|
|
| |
| K, (_W, _H), depth_scale = load_cam_params(replica_root) |
| Ts = load_traj(os.path.join(replica_root, scene, "traj.txt")) |
|
|
| global_mask, used_imgs = build_scene_mask_by_fused_frustums( |
| replica_root=replica_root, |
| scene=scene, |
| grid_pts=grid_pts_world, |
| Ts_cw=Ts, |
| K=K, |
| depth_scale=depth_scale, |
| max_frames=obs_max_frames, |
| stride_frame=obs_stride_frame, |
| obs_stride_pix=obs_stride_pix, |
| max_depth=max_depth, |
| tau=voxel_size, |
| ) |
|
|
| global_mask = optional_mask_dilation(global_mask, dilate_iter=mask_dilate) |
|
|
| |
| unknown = (global_mask < 0.5) |
| global_labels[unknown] = 255 |
|
|
| |
| known_free = (global_mask >= 0.5) & (global_labels == 0) |
| global_labels[known_free] = 0 |
|
|
| out = { |
| "scene_name": scene, |
| "scene_dim": dims, |
| "global_labels": global_labels.astype(np.int64), |
| |
| "global_pts": grid_pts_world.astype(np.float64), |
| "valid_img_count": len(used_imgs), |
| "valid_img_paths": used_imgs, |
| "global_mask": global_mask.astype(np.float64), |
| } |
|
|
| os.makedirs(out_root, exist_ok=True) |
| save_path = os.path.join(out_root, f"{scene}.pkl") |
| with open(save_path, "wb") as f: |
| pickle.dump(out, f, protocol=pickle.HIGHEST_PROTOCOL) |
|
|
| print( |
| f"[OK] {scene}: dim={dims}, labels={np.unique(global_labels).size}, " |
| f"mask_mean={global_mask.mean():.3f}, saved={save_path}" |
| ) |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--replica_root", type=str, required=True, |
| help="Replica_SLAM root (has cam_params.json + scene folders)") |
| ap.add_argument("--preprocessed_dir", type=str, required=True, |
| help="global preprocessed dir (preprocessed/*.npy)") |
| ap.add_argument("--out_dir", type=str, required=True, |
| help="output dir for scene-level pkls") |
| ap.add_argument("--scenes", type=str, default="", |
| help="comma-separated scenes; empty means all under replica_root") |
| ap.add_argument("--voxel_size", type=float, default=0.08) |
| ap.add_argument("--max_depth", type=float, default=10.0) |
|
|
| ap.add_argument("--obs_max_frames", type=int, default=-1) |
| ap.add_argument("--obs_stride_frame", type=int, default=5) |
| ap.add_argument("--obs_stride_pix", type=int, default=1) |
| ap.add_argument("--mask_dilate", type=int, default=0) |
|
|
| args = ap.parse_args() |
|
|
| if args.scenes.strip(): |
| scene_list = [s.strip() for s in args.scenes.split(",") if s.strip()] |
| else: |
| scene_list = [] |
| for s in sorted(os.listdir(args.replica_root)): |
| p = os.path.join(args.replica_root, s, "traj.txt") |
| if os.path.isfile(p): |
| scene_list.append(s) |
|
|
| for scene in scene_list: |
| process_one_scene( |
| replica_root=args.replica_root, |
| out_root=args.out_dir, |
| scene=scene, |
| preprocessed_dir=args.preprocessed_dir, |
| voxel_size=args.voxel_size, |
| max_depth=args.max_depth, |
| obs_max_frames=args.obs_max_frames, |
| obs_stride_frame=args.obs_stride_frame, |
| obs_stride_pix=args.obs_stride_pix, |
| mask_dilate=args.mask_dilate, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|