Download scripts/downscale_to_224.py from behavior-spatial-benchmark/BEHAVIOR-Spatial: direct link, hf CLI and curl.
- Browser
- Download file 7.6 kB
-
https://huggingface.co/datasets/behavior-spatial-benchmark/BEHAVIOR-Spatial/resolve/main/scripts/downscale_to_224.py
- Command line
-
hf download hf://datasets/behavior-spatial-benchmark/BEHAVIOR-Spatial/scripts/downscale_to_224.py
-
curl -L -o downscale_to_224.py https://huggingface.co/datasets/behavior-spatial-benchmark/BEHAVIOR-Spatial/resolve/main/scripts/downscale_to_224.py
7.6 kB
| """Rebuild the 224x224 training inputs used in the paper from the released data. | |
| python scripts/downscale_to_224.py SRC DST [--episodes 0-99] [--workers 8] | |
| SRC is action/train/manipulation or action/train/navigation (LeRobot v2.1). | |
| DST receives a LeRobot v2.1 dataset with every video stream at 224x224: | |
| - RGB streams (head, wrists): each frame resized with cv2.INTER_LINEAR, the | |
| same resize the original 224 conversion applied to the source recordings. | |
| The result matches what the paper's policies trained on to ~39 dB PSNR | |
| (head) / ~40 dB (wrists), but is not byte-identical: that set was resized | |
| straight from the source recordings and encoded once. | |
| - IR streams (manipulation): re-rendered at 224 from meta/ir_centers.jsonl with | |
| the paper's recipe, matching the trained-on IR exactly (up to video coding): | |
| target center scaled 720 -> 224 with round(); dot = radius 4 in #FF3333 over a | |
| 1 px white outline, drawn on the 224 head frame; first-frame stream = frame 0 | |
| of the dot stream repeated; attention map = standalone 224 grid with an | |
| isotropic Gaussian (sigma 8 px) through a jet colormap (background = jet(0); | |
| no target in view => uniform background). Measured against the trained-on | |
| 224 IR: dot ~37 dB, attention map ~52 dB (video-coding noise only). | |
| Parquet data, tasks and norm stats are copied unchanged. Video encoding uses the | |
| LeRobot defaults (libsvtav1, yuv420p, g=2, crf=30). Requires: av, numpy, | |
| opencv-python, pillow. | |
| """ | |
| import argparse, json, os, shutil | |
| from concurrent.futures import ProcessPoolExecutor | |
| import av | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image, ImageDraw | |
| RES, FPS = 224, 30 | |
| DOT_RADIUS, OUTLINE, DOT_COLOR = 4, 1, "#FF3333" | |
| SIGMA, JET_MAX = 8.0, 0.875 | |
| RGB_KEYS = ("head_image", "left_wrist_image", "right_wrist_image") | |
| IR_KEYS = ("object_center_image", "object_center_first_image", "attn_map_image") | |
| def _jet_lut(): | |
| v = np.linspace(0.0, JET_MAX, 256) | |
| ch = [np.clip(1.5 - np.abs(4.0 * v - k), 0.0, 1.0) for k in (3.0, 2.0, 1.0)] | |
| return np.round(np.stack(ch, axis=1) * 255.0).astype(np.uint8) | |
| JET = _jet_lut() | |
| def scale_center(c, src): | |
| s = RES / src | |
| return None if c is None else (int(round(c[0] * s)), int(round(c[1] * s))) | |
| def draw_dot(rgb, c): | |
| if c is None: | |
| return rgb.copy() | |
| img = Image.fromarray(rgb) | |
| d = ImageDraw.Draw(img) | |
| r = DOT_RADIUS + OUTLINE | |
| d.ellipse([c[0] - r, c[1] - r, c[0] + r, c[1] + r], fill="white") | |
| d.ellipse([c[0] - DOT_RADIUS, c[1] - DOT_RADIUS, c[0] + DOT_RADIUS, c[1] + DOT_RADIUS], fill=DOT_COLOR) | |
| return np.asarray(img, dtype=np.uint8) | |
| def heatmap(c): | |
| if c is None: | |
| return np.broadcast_to(JET[0], (RES, RES, 3)).copy() | |
| ys = np.arange(RES, dtype=np.float32)[:, None] | |
| xs = np.arange(RES, dtype=np.float32)[None, :] | |
| g = np.exp(-((xs - c[0]) ** 2 + (ys - c[1]) ** 2) / (2.0 * SIGMA * SIGMA)) | |
| return JET[np.round(255.0 * g).astype(np.uint8)] | |
| def decode(path): | |
| with av.open(path) as c: | |
| return [f.to_ndarray(format="rgb24") for f in c.decode(c.streams.video[0])] | |
| def encode(frames, dst): | |
| os.makedirs(os.path.dirname(dst), exist_ok=True) | |
| tmp = dst + ".tmp.mp4" | |
| with av.open(tmp, "w") as c: | |
| s = c.add_stream("libsvtav1", rate=FPS) | |
| s.width = s.height = RES | |
| s.pix_fmt = "yuv420p" | |
| s.options = {"crf": "30", "g": "2", "preset": "8"} | |
| s.thread_count = 4 # SVT-AV1 can deadlock with unbounded threads | |
| for fr in frames: | |
| for p in s.encode(av.VideoFrame.from_ndarray(np.ascontiguousarray(fr), format="rgb24")): | |
| c.mux(p) | |
| for p in s.encode(): | |
| c.mux(p) | |
| os.replace(tmp, dst) | |
| def image_stats(frames, n=100): | |
| idx = np.linspace(0, len(frames) - 1, min(n, len(frames))).round().astype(int) | |
| x = np.stack([frames[i] for i in idx]).astype(np.float64) / 255.0 | |
| red = lambda f: [[[float(v)]] for v in f(x, axis=(0, 1, 2))] | |
| return {"min": red(np.min), "max": red(np.max), "mean": red(np.mean), "std": red(np.std), "count": [len(idx)]} | |
| def do_episode(args): | |
| src, dst, info, ep, centers = args | |
| vp = info["video_path"] | |
| path = lambda root, k: os.path.join(root, vp.format(episode_chunk=ep // info["chunks_size"], video_key=k, episode_index=ep)) | |
| keys = [k for k, f in info["features"].items() if f["dtype"] == "video"] | |
| stats, head = {}, None | |
| for k in keys: | |
| if k not in RGB_KEYS: | |
| continue | |
| fr = [cv2.resize(f, (RES, RES), interpolation=cv2.INTER_LINEAR) for f in decode(path(src, k))] | |
| if k == "head_image": | |
| head = fr | |
| encode(fr, path(dst, k)) | |
| stats[k] = image_stats(fr) | |
| if any(k in IR_KEYS for k in keys): | |
| cs = [scale_center(c, centers["image_size"]) for c in centers["centers"]] | |
| assert len(cs) == len(head), (ep, len(cs), len(head)) | |
| dot = [draw_dot(f, c) for f, c in zip(head, cs)] | |
| ir = {"object_center_image": dot, "object_center_first_image": [dot[0]] * len(dot), | |
| "attn_map_image": [heatmap(c) for c in cs]} | |
| for k in IR_KEYS: | |
| if k in keys: | |
| encode(ir[k], path(dst, k)) | |
| stats[k] = image_stats(ir[k]) | |
| return ep, stats | |
| def parse_range(s, n): | |
| if not s: | |
| return list(range(n)) | |
| a, b = s.split("-") | |
| return list(range(int(a), min(int(b) + 1, n))) | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("src") | |
| ap.add_argument("dst") | |
| ap.add_argument("--episodes", default="", help="inclusive range for spot checks, e.g. 0-9 (default: all; a subset " | |
| "does not produce a loadable dataset)") | |
| ap.add_argument("--workers", type=int, default=os.cpu_count() // 4 or 1) | |
| a = ap.parse_args() | |
| info = json.load(open(f"{a.src}/meta/info.json")) | |
| eps = parse_range(a.episodes, info["total_episodes"]) | |
| centers = {} | |
| if os.path.exists(f"{a.src}/meta/ir_centers.jsonl"): | |
| for line in open(f"{a.src}/meta/ir_centers.jsonl"): | |
| d = json.loads(line) | |
| if d["episode_index"] in eps: | |
| centers[d["episode_index"]] = d | |
| for sub in ("data",): | |
| shutil.copytree(f"{a.src}/{sub}", f"{a.dst}/{sub}", dirs_exist_ok=True) | |
| os.makedirs(f"{a.dst}/meta", exist_ok=True) | |
| for name in ("meta/episodes.jsonl", "meta/tasks.jsonl", "meta/ir_centers.jsonl", "norm_stats.json", "task_weights.json"): | |
| if os.path.exists(f"{a.src}/{name}"): | |
| shutil.copy2(f"{a.src}/{name}", f"{a.dst}/{name}") | |
| out_info = json.loads(json.dumps(info)) | |
| for f in out_info["features"].values(): | |
| if f["dtype"] == "video": | |
| f["shape"] = [RES, RES, 3] | |
| f["info"]["video.height"] = f["info"]["video.width"] = RES | |
| json.dump(out_info, open(f"{a.dst}/meta/info.json", "w"), indent=4) | |
| new_stats = {} | |
| jobs = [(a.src, a.dst, info, ep, centers.get(ep)) for ep in eps] | |
| with ProcessPoolExecutor(a.workers) as pool: | |
| for i, (ep, st) in enumerate(pool.map(do_episode, jobs)): | |
| new_stats[ep] = st | |
| if i % 50 == 0: | |
| print(f"{i + 1}/{len(eps)} episodes", flush=True) | |
| with open(f"{a.src}/meta/episodes_stats.jsonl") as fi, open(f"{a.dst}/meta/episodes_stats.jsonl", "w") as fo: | |
| for line in fi: | |
| e = json.loads(line) | |
| if e["episode_index"] in new_stats: | |
| e["stats"].update(new_stats[e["episode_index"]]) | |
| fo.write(json.dumps(e) + "\n") | |
| print("done:", a.dst) | |
| if __name__ == "__main__": | |
| main() | |