File size: 11,634 Bytes
01cafbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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()