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B h5 produced by
|
| 2 |
+
``add_pointcloud.py``. This is the final training-ready field that
|
| 3 |
+
``data/hdf5_mshab_dataset.py`` reads.
|
| 4 |
+
|
| 5 |
+
Matches the spec in ``third_party/mshab/DATA.md``:
|
| 6 |
+
|
| 7 |
+
* Foreground only (xyzw[:,:,3] > 0.5)
|
| 8 |
+
* Crop to a box around the robot base_pose:
|
| 9 |
+
x: [base_x - 1.5, base_x + 1.5] m
|
| 10 |
+
y: [base_y - 1.5, base_y + 1.5] m
|
| 11 |
+
z: [base_z + 0.0, base_z + 3.0] m
|
| 12 |
+
* Exactly 1024 points per timestep (random sample w/ replacement if needed)
|
| 13 |
+
* Output format per-timestep: ``[x, y, z, r, g, b]`` where rgb is float in [0,1]
|
| 14 |
+
|
| 15 |
+
Idempotent: if xyzrgb already exists with the right shape & dtype, skip.
|
| 16 |
+
|
| 17 |
+
Usage:
|
| 18 |
+
python add_xyzrgb.py --data-dir path/to/gen_data_save_trajectories [--max-workers 16]
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
import argparse
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import h5py
|
| 26 |
+
import numpy as np
|
| 27 |
+
from tqdm import tqdm
|
| 28 |
+
|
| 29 |
+
N_SAMPLE = 1024
|
| 30 |
+
BOX_XY_HALF = 1.5
|
| 31 |
+
BOX_Z_MIN = 0.0
|
| 32 |
+
BOX_Z_MAX = 3.0
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def compute_xyzrgb(xyzw: np.ndarray, rgb_uint8: np.ndarray, base_pose: np.ndarray,
|
| 36 |
+
rng: np.random.Generator) -> np.ndarray:
|
| 37 |
+
"""xyzw: (N, 4) float32, rgb_uint8: (N, 3) uint8, base_pose: (>=3,) float.
|
| 38 |
+
Returns (1024, 6) float32 — xyz in meters, rgb in [0,1]."""
|
| 39 |
+
# 1. foreground mask
|
| 40 |
+
fg = xyzw[:, 3] > 0.5
|
| 41 |
+
pts = xyzw[fg, :3]
|
| 42 |
+
rgb = rgb_uint8[fg]
|
| 43 |
+
|
| 44 |
+
# 2. crop box around base
|
| 45 |
+
bx, by, bz = float(base_pose[0]), float(base_pose[1]), float(base_pose[2])
|
| 46 |
+
crop = (
|
| 47 |
+
(pts[:, 0] >= bx - BOX_XY_HALF) & (pts[:, 0] <= bx + BOX_XY_HALF) &
|
| 48 |
+
(pts[:, 1] >= by - BOX_XY_HALF) & (pts[:, 1] <= by + BOX_XY_HALF) &
|
| 49 |
+
(pts[:, 2] >= bz + BOX_Z_MIN) & (pts[:, 2] <= bz + BOX_Z_MAX)
|
| 50 |
+
)
|
| 51 |
+
pts = pts[crop]
|
| 52 |
+
rgb = rgb[crop]
|
| 53 |
+
|
| 54 |
+
# 3. fixed-size sample
|
| 55 |
+
if pts.shape[0] == 0:
|
| 56 |
+
# degenerate: no points in box → return zeros
|
| 57 |
+
return np.zeros((N_SAMPLE, 6), dtype=np.float32)
|
| 58 |
+
if pts.shape[0] >= N_SAMPLE:
|
| 59 |
+
idx = rng.choice(pts.shape[0], size=N_SAMPLE, replace=False)
|
| 60 |
+
else:
|
| 61 |
+
idx = rng.choice(pts.shape[0], size=N_SAMPLE, replace=True)
|
| 62 |
+
pts = pts[idx]
|
| 63 |
+
rgb = rgb[idx].astype(np.float32) / 255.0
|
| 64 |
+
return np.concatenate([pts.astype(np.float32), rgb], axis=1)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def process_trajectory(traj_group: h5py.Group) -> tuple[bool, str]:
|
| 68 |
+
if "obs" not in traj_group:
|
| 69 |
+
return False, "no_obs"
|
| 70 |
+
obs = traj_group["obs"]
|
| 71 |
+
if "pointcloud" not in obs:
|
| 72 |
+
return False, "no_pointcloud"
|
| 73 |
+
pc = obs["pointcloud"]
|
| 74 |
+
if "xyzw" not in pc or "rgb" not in pc:
|
| 75 |
+
return False, "missing xyzw/rgb"
|
| 76 |
+
if "extra" not in obs or "base_pose" not in obs["extra"]:
|
| 77 |
+
return False, "missing base_pose"
|
| 78 |
+
|
| 79 |
+
xyzw_all = pc["xyzw"] # (T, N, 4)
|
| 80 |
+
rgb_all = pc["rgb"] # (T, N, 3)
|
| 81 |
+
base_pose = obs["extra"]["base_pose"][:] # (T, 3) or (T, 7)
|
| 82 |
+
T = xyzw_all.shape[0]
|
| 83 |
+
|
| 84 |
+
expected = (T, N_SAMPLE, 6)
|
| 85 |
+
if "xyzrgb" in pc:
|
| 86 |
+
ds = pc["xyzrgb"]
|
| 87 |
+
if tuple(ds.shape) == expected and np.dtype(ds.dtype) == np.float32:
|
| 88 |
+
return True, "already_done"
|
| 89 |
+
del pc["xyzrgb"]
|
| 90 |
+
|
| 91 |
+
rng = np.random.default_rng(2024)
|
| 92 |
+
out = np.empty(expected, dtype=np.float32)
|
| 93 |
+
for t in range(T):
|
| 94 |
+
out[t] = compute_xyzrgb(xyzw_all[t][:], rgb_all[t][:], base_pose[t], rng)
|
| 95 |
+
|
| 96 |
+
pc.create_dataset("xyzrgb", data=out, dtype=np.float32)
|
| 97 |
+
return True, "written"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def process_h5_file(h5_path: Path):
|
| 101 |
+
with h5py.File(h5_path, "r+") as f:
|
| 102 |
+
traj_keys = [k for k in f.keys() if k.startswith("traj_")]
|
| 103 |
+
stats = dict(written=0, already_done=0, skipped=0)
|
| 104 |
+
for tk in tqdm(traj_keys, desc=h5_path.name):
|
| 105 |
+
try:
|
| 106 |
+
ok, reason = process_trajectory(f[tk])
|
| 107 |
+
if reason == "written": stats["written"] += 1
|
| 108 |
+
elif reason == "already_done": stats["already_done"] += 1
|
| 109 |
+
else: stats["skipped"] += 1
|
| 110 |
+
except Exception as e:
|
| 111 |
+
stats["skipped"] += 1
|
| 112 |
+
print(f" [SKIP] {tk}: {type(e).__name__}: {e}")
|
| 113 |
+
print(f"[{h5_path.name}] {stats}")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def iter_h5(data_dir: Path):
|
| 117 |
+
for p in sorted(data_dir.rglob("*.h5")):
|
| 118 |
+
if p.stat().st_size < 1024 * 1024:
|
| 119 |
+
continue
|
| 120 |
+
try:
|
| 121 |
+
with h5py.File(p, "r") as _f:
|
| 122 |
+
_ = list(_f.keys())[:1]
|
| 123 |
+
except Exception as e:
|
| 124 |
+
print(f"[SKIP corrupted] {p}: {e}")
|
| 125 |
+
continue
|
| 126 |
+
yield p
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def main():
|
| 130 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 131 |
+
ap.add_argument("--data-dir", required=True, type=Path)
|
| 132 |
+
args = ap.parse_args()
|
| 133 |
+
|
| 134 |
+
h5s = list(iter_h5(args.data_dir))
|
| 135 |
+
print(f"Found {len(h5s)} h5 file(s):")
|
| 136 |
+
for p in h5s:
|
| 137 |
+
print(f" {p} ({p.stat().st_size/1e9:.1f} GB)")
|
| 138 |
+
|
| 139 |
+
for p in h5s:
|
| 140 |
+
try:
|
| 141 |
+
process_h5_file(p)
|
| 142 |
+
except Exception as e:
|
| 143 |
+
import traceback
|
| 144 |
+
print(f"[ERROR] {p}: {e}"); traceback.print_exc()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
main()
|