File size: 7,601 Bytes
c323605 | 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 | """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()
|