Add multi-view 3D point-track demo video
Browse filesFiles changed (4)
- README.md+6-4
- assets/demo.mp4Added+3
- assets/example.png
- tools/render_demo.pyAdded+276
37 unmodified lines383940414243444552 unmodified lines98991001011021031042 unmodified lines10710810911011111211397 unmodified lines21121221321421521637 unmodified lines- 📷 intrinsics and extrinsics of every camera (per frame for the wrist camera)- 📝 the LIBERO language instruction of every episode<p align="center"><img src="assets/example.png" width="100%" alt="LIBERO-VP example"></p><p align="center"><em>Arm, gripper and target-object points (ringed) projected onto agentview, frontview and the wrist camera (color = point index).</em></p>### Key Modifications52 unmodified lines```LIBERO-VP/├── README.md├── assets/example.png├── manifest.json # every episode -> shard, suite, task, instruction, length; shard sizes and SHA-256├── data/│ ├── libero_10.tar # 500 episodes2 unmodified lines│ ├── libero_object.tar # 500 episodes│ └── libero_spatial.tar # 500 episodes└── tools/└── visualize_sample.py # re-projects the 3D points onto the videos```Each shard holds one directory per episode, named `<suite prefix>_<task>_ep<NNNNNN>` (e.g.97 unmodified lineshf download rooty2020/LIBERO-VP --repo-type dataset --local-dir LIBERO-VPcd LIBERO-VP && mkdir -p extracted && for t in data/*.tar; do tar -xf "$t" -C extracted; donepython tools/visualize_sample.py "extracted/L10_KITCHEN_SCENE3_turn_on_the_stove_and_put_the_moka_pot_on_it_ep000000" --out vis.mp4````manifest.json` lists every episode with its shard, suite, task, instruction and length, plus the size and SHA-256 of37 unmodified lines383940414243444552 unmodified lines98991001011021031042 unmodified lines10710810911011111211311497 unmodified lines21221321421521621721837 unmodified lines- 📷 intrinsics and extrinsics of every camera (per frame for the wrist camera)- 📝 the LIBERO language instruction of every episode<video src="https://huggingface.co/datasets/rooty2020/LIBERO-VP/resolve/main/assets/demo.mp4" poster="https://huggingface.co/datasets/rooty2020/LIBERO-VP/resolve/main/assets/example.png" autoplay loop muted playsinline controls width="100%"></video><p align="center"><em>Two LIBERO-10 episodes. 128 arm and gripper points and 40 points per target object (white rim) are projected onto agentview, frontview and the wrist camera; dot size and brightness follow camera depth, and trails show the last 10 frames (not drawn for the moving wrist camera).</em></p>### Key Modifications52 unmodified lines```LIBERO-VP/├── README.md├── assets/ # demo.mp4 and its poster example.png├── manifest.json # every episode -> shard, suite, task, instruction, length; shard sizes and SHA-256├── data/│ ├── libero_10.tar # 500 episodes2 unmodified lines│ ├── libero_object.tar # 500 episodes│ └── libero_spatial.tar # 500 episodes└── tools/├── visualize_sample.py # re-projects all 3D points onto the videos (calibration check)└── render_demo.py # renders demo videos like the one above```Each shard holds one directory per episode, named `<suite prefix>_<task>_ep<NNNNNN>` (e.g.97 unmodified lineshf download rooty2020/LIBERO-VP --repo-type dataset --local-dir LIBERO-VPcd LIBERO-VP && mkdir -p extracted && for t in data/*.tar; do tar -xf "$t" -C extracted; donepython tools/visualize_sample.py "extracted/L10_KITCHEN_SCENE3_turn_on_the_stove_and_put_the_moka_pot_on_it_ep000000" --out vis.mp4python tools/render_demo.py extracted/<episode> --out demo.mp4 # needs av, matplotlib````manifest.json` lists every episode with its shard, suite, task, instruction and length, plus the size and SHA-256 of
123version https://git-lfs.github.com/spec/v1oid sha256:6cbab607080d36211a7525d50783753ab8a5c466776886c87044c06ec0d4ec4dsize 5134419123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276"""Render a multi-view demo video of the 3D point tracks: all views side by side, persistent points withfading trails, size and brightness from camera depth. No text on the frames.
The clips given on the command line are played back to back (consecutive subtask clips of one episodetile it, so the point identities carry over).
usage: python render_demo.py --out demo.mp4 [--height 384] <clip_dir> [<clip_dir> ...]"""import argparseimport globimport jsonimport os
import cv2import numpy as np
SS = 3 # supersampling of the drawing layer
def view_order(name): return (0, int(name[4:])) if name.startswith("view") and name[4:].isdigit() else (1, name)
def read_video(path): import av
with av.open(path) as c: return np.stack([f.to_ndarray(format="rgb24") for f in c.decode(video=0)])
def load_clip(d): meta = json.load(open(os.path.join(d, "meta.json"))) n = meta["n_frames"] names = sorted(meta["views"], key=view_order) views = {} for v in names: m = meta["views"][v] intr = m["intrinsics"] T = np.asarray(m.get("T_cam_world_perframe", m["T_cam_world"]), np.float64) if T.ndim == 2: T = np.repeat(T[None], n, 0) views[v] = dict( K=np.array([[intr["fx"], 0, intr["cx"]], [0, intr["fy"], intr["cy"]], [0, 0, 1]], np.float64), dist=np.array([intr.get(k, 0.0) for k in ("k1", "k2", "p1", "p2", "k3")], np.float64), wh=(intr["width"], intr["height"]), T=T[:n], rgb=read_video(os.path.join(d, f"{v}.mp4"))[:n]) parts = {} for f in ["robot.npz", "gripper.npz"] + sorted(os.path.basename(p) for p in glob.glob(os.path.join(d, "object*.npz"))): if os.path.isfile(os.path.join(d, f)): parts[f[:-4]] = np.load(os.path.join(d, f))["points"].astype(np.float64)[:n] # view1 camera frame -> world, per frame Tw = np.linalg.inv(views["view1"]["T"]) world = {k: np.einsum("tij,tnj->tni", Tw[:, :3, :3], p) + Tw[:, None, :3, 3] for k, p in parts.items()} return meta, names, views, world
def concat_clips(dirs): clips = [load_clip(d) for d in dirs] names = clips[0][1] views = {v: {k: clips[0][2][v][k] for k in ("K", "dist", "wh")} for v in names} for v in names: views[v]["T"] = np.concatenate([c[2][v]["T"] for c in clips]) views[v]["rgb"] = np.concatenate([c[2][v]["rgb"] for c in clips]) keys = list(clips[0][3]) world = {k: np.concatenate([c[3][k] for c in clips]) for k in keys if all(k in c[3] for c in clips)} return clips[0][0], names, views, world
def farthest(X, k): if k >= len(X): return np.arange(len(X)) sel = [int(np.argmin(np.linalg.norm(X - X.mean(0), axis=1)))] dmin = np.linalg.norm(X - X[sel[0]], axis=1) for _ in range(k - 1): sel.append(int(np.argmax(dmin))) dmin = np.minimum(dmin, np.linalg.norm(X - X[sel[-1]], axis=1)) return np.sort(np.asarray(sel))
def gradient_colors(X, cmap, lo, hi): import matplotlib
Xc = X - X.mean(0) _, _, Vt = np.linalg.svd(Xc, full_matrices=False) p = Xc @ Vt[:2].T a = (p[:, 0] - p[:, 0].min()) / max(np.ptp(p[:, 0]), 1e-9) b = (p[:, 1] - p[:, 1].min()) / max(np.ptp(p[:, 1]), 1e-9) rgb = matplotlib.colormaps[cmap](lo + (hi - lo) * a)[:, :3] * (0.85 + 0.15 * b)[:, None] return np.clip(rgb, 0, 1)
OBJECT_CMAPS = [("spring", 0.0, 0.55), ("cool", 0.35, 1.0), ("Wistia", 0.2, 1.0), ("PuRd", 0.45, 0.95)]
def select_points(world, targets, n_body, n_object): """Farthest-point subsampling on the frame-0 shape: arm and gripper together (even spacing over the whole robot), then each object; fixed colour per point.""" pts, cols, is_obj = [], [], [] body = [world[k] for k in ("robot", "gripper") if k in world] if body: B = np.concatenate(body, 1) B = B[:, farthest(B[0], n_body)] pts.append(B) cols.append(gradient_colors(B[0], "turbo", 0.08, 0.92)) is_obj.append(np.zeros(B.shape[1], bool)) objs = [] for k in sorted(k for k in world if k.startswith("object")): O = world[k] sizes = targets.get(k) if sizes and sum(sizes) == O.shape[1] and len(sizes) > 1: # several targets packed in one file objs += np.split(O, np.cumsum(sizes)[:-1], axis=1) else: objs.append(O) for i, O in enumerate(objs): O = O[:, farthest(O[0], n_object)] cm, lo, hi = OBJECT_CMAPS[i % len(OBJECT_CMAPS)] pts.append(O) cols.append(gradient_colors(O[0], cm, lo, hi)) is_obj.append(np.ones(O.shape[1], bool)) return np.concatenate(pts, 1), (np.concatenate(cols) * 255).astype(np.uint8), np.concatenate(is_obj)
def project(view, Xw, scale): """[T,N,3] world -> uv [T,N,2] output pixels, depth [T,N], valid [T,N].""" T = view["T"] Xc = np.einsum("tij,tnj->tni", T[:, :3, :3], Xw) + T[:, None, :3, 3] z = Xc[..., 2] w, h = view["wh"] K = view["K"] uv = np.zeros(Xc.shape[:2] + (2,)) ok = z > 0.05 x = Xc[..., 0] / np.where(ok, z, 1) y = Xc[..., 1] / np.where(ok, z, 1) u0, v0 = K[0, 0] * x + K[0, 2], K[1, 1] * y + K[1, 2] ok &= (u0 > -0.1 * w) & (u0 < 1.1 * w) & (v0 > -0.1 * h) & (v0 < 1.1 * h) # trust distortion only near the image if np.any(view["dist"]): sel = np.nonzero(ok) p, _ = cv2.projectPoints(Xc[sel].reshape(-1, 1, 3), np.zeros(3), np.zeros(3), K, view["dist"]) uv[sel] = p.reshape(-1, 2) else: uv[..., 0], uv[..., 1] = u0, v0 uv = (uv + 0.5) * scale - 0.5 return uv, z, ok
def draw(frame, uv, z, ok, cols, is_obj, t, tail, base_r): H, W = frame.shape[:2] h, w = H * SS, W * SS rgb = np.zeros((h, w, 3), np.uint8) a = np.zeros((h, w), np.uint8) P = uv * SS inside = ok & (uv[..., 0] >= -2) & (uv[..., 0] < W + 2) & (uv[..., 1] >= -2) & (uv[..., 1] < H + 2) zt = z[t][inside[t]] zref = np.median(zt) if len(zt) else 1.0 rad = np.clip(base_r * zref / np.maximum(z, 1e-3), 0.65 * base_r, 1.6 * base_r) rad = np.where(is_obj[None], rad * 1.15, rad) near = np.clip((zref - z) / max(0.25 * zref, 1e-3), -1, 1) # >0 nearer than the median shade = 0.82 + 0.18 * near # trails: oldest segment first for k in range(tail, 0, -1): t0, t1 = t - k, t - k + 1 if t0 < 0: continue f = 1 - (k - 1) / tail al = int(255 * (0.05 + 0.55 * f ** 1.5)) seg = np.nonzero(inside[t0] & inside[t1])[0] for n in seg: th = max(1, int(round(SS * rad[t1, n] * (0.25 + 0.45 * f)))) p0 = tuple(int(round(c * 16)) for c in P[t0, n]) p1 = tuple(int(round(c * 16)) for c in P[t1, n]) c = tuple(int(x) for x in cols[n] * shade[t1, n]) cv2.line(rgb, p0, p1, c, th, cv2.LINE_AA, shift=4) cv2.line(a, p0, p1, al, th, cv2.LINE_AA, shift=4) # dots: far first, near on top; rim (dark on the robot, white on objects), colour body, highlight order = np.argsort(-z[t]) for n in order: if not inside[t, n]: continue cen = tuple(int(round(c * 16)) for c in P[t, n]) r = rad[t, n] * SS col = cols[n].astype(np.float32) * shade[t, n] rim = (255, 255, 255) if is_obj[n] else tuple(int(x) for x in col * 0.35) cv2.circle(rgb, cen, int(round((r + 0.9 * SS) * 16)), rim, -1, cv2.LINE_AA, shift=4) cv2.circle(a, cen, int(round((r + 0.9 * SS) * 16)), 235, -1, cv2.LINE_AA, shift=4) cv2.circle(rgb, cen, int(round(r * 16)), tuple(int(x) for x in col), -1, cv2.LINE_AA, shift=4) hl = tuple(int(round((c - 0.3 * r) * 16)) for c in P[t, n]) hcol = tuple(int(min(255, x * 0.55 + 255 * 0.45)) for x in col) cv2.circle(rgb, hl, int(round(0.38 * r * 16)), hcol, -1, cv2.LINE_AA, shift=4) af = a.astype(np.float32) / 255.0 pre = rgb.astype(np.float32) / 255.0 * af[..., None] pre = cv2.resize(pre, (W, H), interpolation=cv2.INTER_AREA) af = cv2.resize(af, (W, H), interpolation=cv2.INTER_AREA) return np.clip(frame.astype(np.float32) * (1 - af[..., None]) + pre * 255.0, 0, 255).round().astype(np.uint8)
class Writer: def __init__(self, path, w, h, fps, crf): import av
self.c = av.open(path, "w", options={"movflags": "+faststart"}) self.s = self.c.add_stream("libx264", rate=int(fps)) self.s.width, self.s.height, self.s.pix_fmt = w, h, "yuv420p" self.s.options = {"crf": str(crf), "preset": "slow", "threads": "8"}
def write(self, frame): import av
for p in self.s.encode(av.VideoFrame.from_ndarray(np.ascontiguousarray(frame), format="rgb24")): self.c.mux(p)
def close(self): for p in self.s.encode(): self.c.mux(p) self.c.close()
def main(): ap = argparse.ArgumentParser() ap.add_argument("clips", nargs="+") ap.add_argument("--out", required=True) ap.add_argument("--height", type=int, default=384, help="height of each view in the output") ap.add_argument("--n-body", type=int, default=128, help="points on arm + gripper") ap.add_argument("--n-object", type=int, default=40) ap.add_argument("--tail", type=int, default=10) ap.add_argument("--radius", type=float, default=0.011, help="dot radius as a fraction of the view height") ap.add_argument("--views", default=None, help="comma-separated subset/order of views") ap.add_argument("--gap", type=int, default=4, help="white gap between views (px)") ap.add_argument("--crf", type=int, default=20) ap.add_argument("--poster", default=None, help="PNG of frame --poster-frame") ap.add_argument("--poster-frame", type=float, default=0.5, help="fraction of the video") args = ap.parse_args()
meta, names, views, world = concat_clips(args.clips) if args.views: names = args.views.split(",") obj = meta.get("object") if isinstance(meta.get("object"), dict) else {} targets = {"object": [t["n_points"] for t in obj.get("targets", []) if "n_points" in t]} Xw, cols, is_obj = select_points(world, targets, args.n_body, args.n_object) n_t = Xw.shape[0] tiles = [] for v in names: vw = views[v] h0, w0 = vw["rgb"].shape[1:3] s = args.height / h0 W = int(round(w0 * s / 2)) * 2 uv, z, ok = project(vw, Xw, np.array([W / w0, args.height / h0])) if (w0, h0) != tuple(vw["wh"]): raise ValueError(f"{v}: video {w0}x{h0} != intrinsics {vw['wh']}") T = vw["T"] centers = -np.einsum("tji,tj->ti", T[:, :3, :3], T[:, :3, 3]) moving = np.linalg.norm(centers - centers[0], axis=1).max() > 0.01 tiles.append(dict(v=v, W=W, uv=uv, z=z, ok=ok, tail=0 if moving else args.tail)) width = sum(t["W"] for t in tiles) + args.gap * (len(tiles) - 1) width += width % 2 fps = meta.get("fps", 15) wr = Writer(args.out, width, args.height, fps, args.crf) poster_t = int(args.poster_frame * (n_t - 1)) for t in range(n_t): row = [] for i, tl in enumerate(tiles): fr = cv2.resize(views[tl["v"]]["rgb"][t], (tl["W"], args.height), interpolation=cv2.INTER_LANCZOS4 if tl["W"] > views[tl["v"]]["rgb"].shape[2] else cv2.INTER_AREA) row.append(draw(fr, tl["uv"], tl["z"], tl["ok"], cols, is_obj, t, tl["tail"], args.radius * args.height)) if i < len(tiles) - 1: row.append(np.full((args.height, args.gap, 3), 255, np.uint8)) canvas = np.concatenate(row, 1) if canvas.shape[1] < width: canvas = np.pad(canvas, ((0, 0), (0, width - canvas.shape[1]), (0, 0)), constant_values=255) wr.write(canvas) if args.poster and t == poster_t: cv2.imwrite(args.poster, canvas[..., ::-1]) wr.close() print(f"{args.out}: {len(tiles)} views, {Xw.shape[1]} points ({int(is_obj.sum())} on objects), {n_t} frames @ {fps} fps, {width}x{args.height}")
if __name__ == "__main__": main()README.md+6-4
assets/demo.mp4Added+3
assets/example.png

Large File Pointer Details
- SHA256: 43bd110671a2579767043923988ec1cd9de39c030e4d6f7ccea08cd132309e2d
- Pointer size: 131 Bytes
- Size of remote file: 248 kB

Large File Pointer Details
- SHA256: 680f5e3d799fa5c966eb64fd141ad9445e2ca6679534de0d9d9b3704852d9b9d
- Pointer size: 131 Bytes
- Size of remote file: 571 kB
tools/render_demo.pyAdded+276