ReplicaOcc / prepare_preprocessed.py
the-masses's picture
Add files using upload-large-folder tool
01cafbe verified
"""
bash:
python prepare_preprocessed.py \
--replica_root ./Replica_SLAM \
--out_root ./Replica_OCC \
--stride 4 \
--depth_scale -1 \
--max_depth 10.0 \
--max_frames -1
"""
import os
import glob
import json
import argparse
from tqdm import tqdm
import numpy as np
import cv2
from PIL import Image
from mmengine import track_parallel_progress
# ---- globals for multiprocessing workers ----
_G_REPLICA_ROOT = None
_G_OUT_PREPROCESSED = None
_G_MAX_FRAMES = None
_G_STRIDE = None
_G_DEPTH_SCALE = None
_G_MAX_DEPTH = None
# -----------------------------
# Replica-specific IO
# -----------------------------
def _try_load_intrinsics(scene_dir):
"""Load intrinsics for Replica-SLAM format.
Priority:
1) scene_dir/* (intrinsic.txt, intrinsics.txt, cam.txt, camera.txt)
2) dataset_root/cam_params.json (sibling of scene folders)
Returns:
K4: 4x4 float32
depth_scale_from_file: float or None
"""
# 1) old candidates inside scene_dir
candidates = [
os.path.join(scene_dir, "intrinsic.txt"),
os.path.join(scene_dir, "intrinsics.txt"),
os.path.join(scene_dir, "cam.txt"),
os.path.join(scene_dir, "camera.txt"),
]
for p in candidates:
if os.path.exists(p):
K = np.loadtxt(p)
K = np.asarray(K)
if K.ndim == 1 and K.size == 4:
fx, fy, cx, cy = K.tolist()
KK = np.eye(4, dtype=np.float32)
KK[0, 0] = fx
KK[1, 1] = fy
KK[0, 2] = cx
KK[1, 2] = cy
return KK, None
if K.shape == (3, 3):
KK = np.eye(4, dtype=np.float32)
KK[:3, :3] = K
return KK, None
if K.shape == (4, 4):
return K.astype(np.float32), None
# 2) Replica-SLAM common: cam_params.json at dataset root (scene_dir/..)
dataset_root = os.path.dirname(scene_dir)
json_path = os.path.join(dataset_root, "cam_params.json")
if os.path.exists(json_path):
with open(json_path, "r") as f:
js = json.load(f)
cam = js.get("camera", js) # tolerate either {"camera":{...}} or flat
fx = float(cam["fx"])
fy = float(cam["fy"])
cx = float(cam["cx"])
cy = float(cam["cy"])
KK = np.eye(4, dtype=np.float32)
KK[0, 0] = fx
KK[1, 1] = fy
KK[0, 2] = cx
KK[1, 2] = cy
depth_scale = cam.get("scale", None)
depth_scale = float(depth_scale) if depth_scale is not None else None
return KK, depth_scale
raise FileNotFoundError(
f"Cannot find intrinsics. Tried {candidates} and {json_path}"
)
def _load_traj_as_Tcw_list(traj_path):
"""Load traj.txt and return list of 4x4 matrices extCam2World (Tcw)."""
arr = np.loadtxt(traj_path)
arr = np.asarray(arr)
if arr.ndim == 3 and arr.shape[-2:] == (4, 4):
return [arr[i] for i in range(arr.shape[0])]
if arr.ndim == 1:
if arr.size == 16:
return [arr.reshape(4, 4)]
if arr.size == 12:
T = np.eye(4, dtype=np.float32)
T[:3, :] = arr.reshape(3, 4)
return [T]
raise ValueError(f"Unexpected traj format (1D) in {traj_path}: size={arr.size}")
if arr.ndim == 2:
if arr.shape[1] == 16:
return [arr[i].reshape(4, 4) for i in range(arr.shape[0])]
if arr.shape[1] == 12:
out = []
for i in range(arr.shape[0]):
T = np.eye(4, dtype=np.float32)
T[:3, :] = arr[i].reshape(3, 4)
out.append(T)
return out
raise ValueError(f"Unexpected traj format in {traj_path}: shape={arr.shape}")
def _backproject_depth_to_world(depth_m, sem_id, Tcw, K4, stride=4, max_depth=10.0):
"""Backproject depth + semantic_id image to world points with labels."""
K = K4[:3, :3]
fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]
H, W = depth_m.shape
ys = np.arange(0, H, stride)
xs = np.arange(0, W, stride)
grid_y, grid_x = np.meshgrid(ys, xs, indexing="ij")
u = grid_x.reshape(-1)
v = grid_y.reshape(-1)
d = depth_m[v, u]
lab = sem_id[v, u].astype(np.int32)
valid = (d > 1e-6) & (d < max_depth)
u = u[valid]
v = v[valid]
d = d[valid]
lab = lab[valid]
# camera coordinates
x = (u - cx) * d / fx
y = (v - cy) * d / fy
z = d
pts_cam = np.stack([x, y, z], axis=1)
# world coordinates: Xw = R * Xc + t (Tcw)
R = Tcw[:3, :3]
t = Tcw[:3, 3]
pts_w = (R @ pts_cam.T).T + t[None, :]
return pts_w, lab
def _voxelize_points_majority(points, labels, voxUnit=0.08):
"""Voxelize points to a grid of size voxUnit, assign semantic label by majority vote.
Returns (N,7) [x,y,z,r,g,b,label] with rgb filled zeros.
"""
# quantize to voxel centers
q = np.floor(points / voxUnit + 0.5).astype(np.int64) # integer voxel index
# group by voxel index
keys = q[:, 0].astype(np.int64), q[:, 1].astype(np.int64), q[:, 2].astype(np.int64)
key = np.stack(keys, axis=1)
# sort by key
order = np.lexsort((key[:, 2], key[:, 1], key[:, 0]))
key = key[order]
labels = labels[order]
out_xyz = []
out_lab = []
start = 0
n = key.shape[0]
while start < n:
end = start + 1
while end < n and np.all(key[end] == key[start]):
end += 1
labs = labels[start:end]
labs_valid = labs[labs > 0]
if len(labs_valid) == 0:
maj = 0
else:
maj = np.bincount(labs_valid).argmax()
voxel_center = key[start].astype(np.float32) * voxUnit
out_xyz.append(voxel_center)
out_lab.append(maj)
start = end
out_xyz = np.stack(out_xyz, axis=0)
out_lab = np.asarray(out_lab, dtype=np.int32).reshape(-1, 1)
rgb = np.zeros((out_xyz.shape[0], 3), dtype=np.uint8)
vox = np.hstack([out_xyz.astype(np.float32), rgb.astype(np.float32), out_lab.astype(np.float32)]) # (N,7)
return vox
# -----------------------------
# Step 0: build "preprocessed/<scene>.npy"
# -----------------------------
def preprocess_replica_scene(scene_name, replica_root, out_preprocessed,
max_frames=-1, stride=4, depth_scale=1000.0, max_depth=10.0,
verbose=False):
"""
Build OccScanNet-like preprocessed voxel list for a Replica scene:
output: out_preprocessed/<scene>.npy (N,7): [x,y,z,r,g,b,label]
"""
scene_dir = os.path.join(replica_root, scene_name)
if not os.path.isdir(scene_dir):
return
traj_path = os.path.join(scene_dir, "traj.txt")
if not os.path.exists(traj_path):
raise FileNotFoundError(f"traj.txt not found in {scene_dir}")
# inputs
depth_paths = sorted(glob.glob(os.path.join(scene_dir, "depths", "depth*.png")))
sem_paths = sorted(glob.glob(os.path.join(scene_dir, "semantic_ids", "semantic_id*.png")))
if len(depth_paths) == 0 or len(sem_paths) == 0:
raise FileNotFoundError(f"depths/ or semantic_ids/ missing or empty in {scene_dir}")
# align by index (assume same count/order)
n = min(len(depth_paths), len(sem_paths))
depth_paths = depth_paths[:n]
sem_paths = sem_paths[:n]
Tcw_list = _load_traj_as_Tcw_list(traj_path)
n = min(n, len(Tcw_list))
depth_paths = depth_paths[:n]
sem_paths = sem_paths[:n]
Tcw_list = Tcw_list[:n]
if max_frames is not None and max_frames > 0:
n = min(n, max_frames)
depth_paths = depth_paths[:n]
sem_paths = sem_paths[:n]
Tcw_list = Tcw_list[:n]
K4, file_depth_scale = _try_load_intrinsics(scene_dir)
all_pts = []
all_lab = []
it = range(n)
if verbose:
it = tqdm(it, desc=f"[preprocess] {scene_name}", leave=False)
for i in it:
# depth
d16 = Image.open(depth_paths[i]).convert("I;16")
d16 = np.array(d16).astype(np.float32)
use_scale = float(depth_scale)
if (use_scale is None) or (use_scale <= 0):
if file_depth_scale is None:
raise ValueError("depth_scale not provided and cam_params.json has no 'scale'")
use_scale = float(file_depth_scale)
depth_m = d16 / use_scale
# semantic id (assume 8-bit or 16-bit; keep as int)
sem = Image.open(sem_paths[i])
sem = np.array(sem).astype(np.int32)
pts_w, lab = _backproject_depth_to_world(
depth_m=depth_m,
sem_id=sem,
Tcw=Tcw_list[i],
K4=K4,
stride=stride,
max_depth=max_depth,
)
if pts_w.shape[0] == 0:
continue
all_pts.append(pts_w)
all_lab.append(lab)
if len(all_pts) == 0:
raise RuntimeError(f"No valid backprojected points for scene {scene_name}")
all_pts = np.concatenate(all_pts, axis=0)
all_lab = np.concatenate(all_lab, axis=0)
# voxelize -> (N,7)
vox = _voxelize_points_majority(all_pts, all_lab, voxUnit=0.08)
os.makedirs(out_preprocessed, exist_ok=True)
np.save(os.path.join(out_preprocessed, f"{scene_name}.npy"), vox)
return True
# -----------------------------
# multiprocessing worker
# -----------------------------
def worker_preprocess_scene(scene_name):
return preprocess_replica_scene(
scene_name=scene_name,
replica_root=_G_REPLICA_ROOT,
out_preprocessed=_G_OUT_PREPROCESSED,
max_frames=_G_MAX_FRAMES,
stride=_G_STRIDE,
depth_scale=_G_DEPTH_SCALE,
max_depth=_G_MAX_DEPTH,
verbose=False,
)
# -----------------------------
# Main
# -----------------------------
def parse_args():
p = argparse.ArgumentParser("Prepare Replica -> preprocessed voxels (Step 0 only)")
p.add_argument("--replica_root", type=str, required=True,
help="Path to Replica-SLAM root, containing office0/room0/..")
p.add_argument("--out_root", type=str, required=True,
help="Output root. Will create preprocessed/")
p.add_argument("--nproc", type=int, default=1)
p.add_argument("--max_frames", type=int, default=-1,
help="Use first N frames per scene for building global preprocessed voxels; -1 means all.")
p.add_argument("--stride", type=int, default=4,
help="Pixel stride for backprojection when building global preprocessed voxels.")
p.add_argument("--depth_scale", type=float, default=-1,
help="depth_m = depth_png / depth_scale. Common: 1000 if png in mm.")
p.add_argument("--max_depth", type=float, default=10.0)
return p.parse_args()
def main():
args = parse_args()
replica_root = args.replica_root
out_root = args.out_root
out_preprocessed = os.path.join(out_root, "preprocessed")
os.makedirs(out_preprocessed, exist_ok=True)
scene_list = sorted([d for d in os.listdir(replica_root)
if os.path.isdir(os.path.join(replica_root, d))])
global _G_REPLICA_ROOT, _G_OUT_PREPROCESSED, _G_MAX_FRAMES, _G_STRIDE, _G_DEPTH_SCALE, _G_MAX_DEPTH
_G_REPLICA_ROOT = replica_root
_G_OUT_PREPROCESSED = out_preprocessed
_G_MAX_FRAMES = args.max_frames
_G_STRIDE = args.stride
_G_DEPTH_SCALE = args.depth_scale
_G_MAX_DEPTH = args.max_depth
# Run the selected preprocessing tasks.
track_parallel_progress(worker_preprocess_scene, scene_list, nproc=args.nproc)
print("===== Finish Step 0 (preprocessed) =====")
if __name__ == "__main__":
main()