agentworldmodel / visualize_fused_pcd.py
ChongkaiGao's picture
Add visualize_fused_pcd.py: viewer / video renderer for the fused and downsampled point-cloud trajectories
ce16a0c verified
Raw History Blame Contribute Delete
10.5 kB
#!/usr/bin/env python3
"""Visualize the point-cloud trajectory of one episode of the agentworldmodel dataset.
Self-contained (numpy, open3d, opencv-python): works on a downloaded episode folder without the
recording code.
pip install numpy open3d opencv-python
Each episode folder (e.g. sweep/episode_0003/) holds two point-cloud sequences, both in the LEFT
arm base frame (x forward, z up, metres):
fused/<seq>.npz the fused cloud of all four RGB-D cameras, cropped to the table volume,
~16 Hz: points (N,3) float32, colors (N,3) uint8 RGB, t (capture time, s),
cam_poses, q_left / q_right (joints read with the frames)
pc_downsampled.npz fixed-size clouds, one per fused cloud: points (T,832,3), colors, labels
(0 table x64, 1 scene x512, 2 left gripper x128, 3 right gripper x128), t
Usage:
python visualize_fused_pcd.py sweep/episode_0003 # interactive window
python visualize_fused_pcd.py sweep/episode_0003 --source downsampled
python visualize_fused_pcd.py sweep/episode_0003 --video ep3.mp4 # render to video (needs a display / X server)
Interactive keys: Space play/pause N / B next / previous frame [ / ] slower / faster
T table box on/off S screenshot Q or Esc quit
Mouse: drag to rotate, scroll to zoom, shift+drag to pan.
"""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
from typing import List, Optional, Tuple
import cv2
import numpy as np
import open3d as o3d
LABEL_COLOURS = {0: (0.45, 0.45, 0.5), 2: (0.25, 0.85, 0.3), 3: (1.0, 0.6, 0.15)}
"""downsampled: table grey, left gripper green, right gripper orange; scene points keep their RGB."""
def load_fused(ep: Path) -> List[Tuple[float, np.ndarray, np.ndarray]]:
files = sorted((ep / "fused").glob("*.npz"))
if not files:
raise SystemExit(f"no fused clouds in {ep / 'fused'}")
out = []
for f in files:
d = np.load(f)
out.append((float(d["t"]), d["points"].astype(np.float64), d["colors"].astype(np.float64) / 255.0))
return out
def load_downsampled(ep: Path, colour_labels: bool = True) -> List[Tuple[float, np.ndarray, np.ndarray]]:
d = np.load(ep / "pc_downsampled.npz")
lab = d["labels"]
out = []
for i in range(len(d["t"])):
P = d["points"][i].astype(np.float64)
C = d["colors"][i].astype(np.float64) / 255.0
if colour_labels:
for k, c in LABEL_COLOURS.items():
C[lab == k] = c
ok = np.all(np.isfinite(P), axis=1)
out.append((float(d["t"][i]), P[ok], C[ok]))
return out
def table_box(ep: Path) -> Optional[o3d.geometry.LineSet]:
"""The crop volume (table rectangle up to its height band) as a wireframe, from table_region.json."""
f = ep / "table_region.json"
if not f.exists():
return None
r = json.loads(f.read_text())
T = np.array(r["T_lb_table"])
hx, hy = r["half_size"]
_, z1 = r["z_range"]
c = np.array([[-hx, -hy], [hx, -hy], [hx, hy], [-hx, hy]])
pts = []
for z in (0.0, z1):
for x, y in c:
pts.append(T[:3, :3] @ np.array([x, y, z]) + T[:3, 3])
lines = [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7]]
ls = o3d.geometry.LineSet(o3d.utility.Vector3dVector(np.array(pts)), o3d.utility.Vector2iVector(lines))
ls.colors = o3d.utility.Vector3dVector(np.tile([[0.5, 0.5, 0.5]], (len(lines), 1)))
return ls
def table_centre(ep: Path) -> np.ndarray:
f = ep / "table_region.json"
if f.exists():
return np.array(json.loads(f.read_text())["T_lb_table"])[:3, 3]
return np.array([0.4, -0.3, 0.1])
class Player:
def __init__(self, frames: List[Tuple[float, np.ndarray, np.ndarray]], ep: Path, point_size: float, speed: float) -> None:
self.f, self.ep, self.point_size, self.speed = frames, ep, point_size, speed
self.i, self.playing, self.last = 0, True, time.monotonic()
self.pc = o3d.geometry.PointCloud()
self.box = table_box(ep)
self.show_box = True
def set(self, i: int) -> None:
_, P, C = self.f[i]
self.pc.points = o3d.utility.Vector3dVector(P if len(P) else np.zeros((1, 3)))
self.pc.colors = o3d.utility.Vector3dVector(C if len(C) else np.zeros((1, 3)))
def view(self, vis: o3d.visualization.Visualizer) -> None:
opt = vis.get_render_option()
opt.point_size = self.point_size
opt.background_color = np.array([0.12, 0.12, 0.14])
ctr = vis.get_view_control()
ctr.set_lookat(table_centre(self.ep))
ctr.set_front([-0.55, 0.2, 0.81]) # from behind the arms, looking down onto the table
ctr.set_up([0.0, 0.0, 1.0])
ctr.set_zoom(0.36)
def status(self) -> None:
t, P, _ = self.f[self.i]
print(f"\r[frame {self.i + 1}/{len(self.f)}] t {t - self.f[0][0]:6.2f} s {len(P)} pts {'playing' if self.playing else 'paused '} x{self.speed:.2f} ", end="", flush=True)
def run(self) -> None:
vis = o3d.visualization.VisualizerWithKeyCallback()
vis.create_window(f"point cloud -- {self.ep.parent.name}/{self.ep.name}", width=1400, height=900)
self.set(0)
vis.add_geometry(self.pc)
if self.box is not None:
vis.add_geometry(self.box)
vis.add_geometry(o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.1))
self.view(vis)
def upd(v: o3d.visualization.Visualizer) -> None:
self.set(self.i)
v.update_geometry(self.pc)
self.status()
def step(d: int): # noqa: ANN202
def cb(v: o3d.visualization.Visualizer) -> bool:
self.i = (self.i + d) % len(self.f)
upd(v)
return False
return cb
def play(v: o3d.visualization.Visualizer) -> bool:
self.playing = not self.playing
self.last = time.monotonic()
self.status()
return False
def speed(k: float): # noqa: ANN202
def cb(v: o3d.visualization.Visualizer) -> bool:
self.speed = float(np.clip(self.speed * k, 0.125, 8.0))
self.status()
return False
return cb
def box(v: o3d.visualization.Visualizer) -> bool:
if self.box is not None:
self.show_box = not self.show_box
(v.add_geometry if self.show_box else v.remove_geometry)(self.box, reset_bounding_box=False)
return False
def shot(v: o3d.visualization.Visualizer) -> bool:
path = Path.cwd() / f"{self.ep.name}_frame_{self.i:04d}.png"
v.capture_screen_image(str(path), do_render=True)
print(f"\n[shot] {path}")
return False
def quit_(v: o3d.visualization.Visualizer) -> bool:
v.close()
return False
for key, cb in ((" ", play), ("N", step(1)), ("B", step(-1)), ("]", speed(2.0)), ("[", speed(0.5)), ("T", box), ("S", shot), ("Q", quit_)):
vis.register_key_callback(ord(key), cb)
vis.register_key_callback(256, quit_) # Esc
self.status()
while vis.poll_events():
if self.playing and len(self.f) > 1:
j = (self.i + 1) % len(self.f)
gap = self.f[j][0] - self.f[self.i][0] if j else 0.5
if time.monotonic() - self.last >= max(gap, 0.0) / self.speed:
self.i, self.last = j, time.monotonic()
upd(vis)
vis.update_renderer()
time.sleep(0.005)
vis.destroy_window()
print()
def render(self, path: Path, size: Tuple[int, int], title: str) -> None:
w, h = size
vis = o3d.visualization.Visualizer()
vis.create_window(width=w, height=h, visible=False)
self.set(0)
vis.add_geometry(self.pc)
if self.box is not None:
vis.add_geometry(self.box)
self.view(vis)
ts = np.array([f[0] for f in self.f])
fps = float(np.clip(1.0 / np.median(np.diff(ts)) if len(ts) > 1 else 10.0, 1.0, 30.0)) * self.speed
out = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
for i in range(len(self.f)):
self.set(i)
vis.update_geometry(self.pc)
vis.poll_events()
vis.update_renderer()
img = cv2.cvtColor((np.asarray(vis.capture_screen_float_buffer(do_render=True)) * 255).astype(np.uint8), cv2.COLOR_RGB2BGR)
cv2.putText(img, f"{title} {i + 1}/{len(self.f)} t {self.f[i][0] - self.f[0][0]:5.2f} s {len(self.f[i][1])} pts", (14, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (230, 230, 230), 2)
out.write(img)
out.release()
vis.destroy_window()
print(f"[video] {path}: {len(self.f)} frames at {fps:.1f} fps ({len(self.f) / fps:.1f} s)")
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("episode", help="episode folder, e.g. sweep/episode_0003")
ap.add_argument("--source", choices=("fused", "downsampled"), default="fused", help="fused clouds (default) or pc_downsampled.npz")
ap.add_argument("--rgb", action="store_true", help="downsampled: keep observed colours instead of label colours")
ap.add_argument("--video", help="render to this .mp4 instead of opening a window")
ap.add_argument("--size", type=int, nargs=2, default=(1280, 800), metavar=("W", "H"))
ap.add_argument("--point-size", type=float, default=None)
ap.add_argument("--speed", type=float, default=1.0, help="playback speed relative to real time")
a = ap.parse_args()
ep = Path(a.episode).expanduser()
frames = load_fused(ep) if a.source == "fused" else load_downsampled(ep, colour_labels=not a.rgb)
span = frames[-1][0] - frames[0][0]
print(f"[load] {ep}: {len(frames)} frames over {span:.1f} s, {np.mean([len(f[1]) for f in frames]):.0f} points each")
ps = a.point_size if a.point_size is not None else (2.0 if a.source == "fused" else 6.0)
player = Player(frames, ep, ps, a.speed)
if a.video:
player.render(Path(a.video).expanduser(), tuple(a.size), f"{ep.parent.name}/{ep.name} [{a.source}]")
else:
player.run()
if __name__ == "__main__":
main()