| |
| """Visualize policy-input subgoal keyframes (same style as compute_subgoal_embedding). |
| |
| Sampling matches train_policy.py / RoboSuiteDataset.sample_goal_sequence_paths. |
| Preprocessing matches encode_goals_with_r3m: raw demo PNG -> Resize(224) -> [0,1] tensor. |
| (No CenterCrop; RoboSuiteDataset transform is NOT used for subgoal encoding.) |
| """ |
|
|
| import argparse |
| import glob |
| import os |
|
|
| import matplotlib.pyplot as plt |
| import numpy as np |
| import torchvision.transforms as T |
| from PIL import Image |
|
|
|
|
| def save_keyframe_visualization(sampled_images, save_path): |
| """Same layout as multi-task-tcc-robosuite/compute_subgoal_embedding.py.""" |
| sampled_images = np.squeeze(sampled_images) |
| num_trajectories = sampled_images.shape[0] |
| num_keyframes = sampled_images.shape[1] |
|
|
| fig, axes = plt.subplots( |
| num_trajectories, |
| num_keyframes, |
| figsize=(num_keyframes * 2, num_trajectories * 2), |
| ) |
|
|
| for i in range(num_trajectories): |
| for j in range(num_keyframes): |
| ax = axes[i, j] if num_trajectories > 1 else axes[j] |
| img = sampled_images[i, j].transpose(1, 2, 0) |
| ax.imshow(img) |
| ax.axis("off") |
|
|
| plt.tight_layout() |
| plt.savefig(save_path) |
| plt.close() |
| print(f"Saved keyframe visualization to {save_path}.") |
|
|
|
|
| def build_r3m_display_transform(size=224): |
| """Same resize path as train_policy.encode_goals_with_r3m (display only).""" |
| return T.Compose([ |
| T.ToPILImage(), |
| T.Resize(size), |
| T.ToTensor(), |
| ]) |
|
|
|
|
| def load_demo_dirs(demo_root): |
| dirs = sorted( |
| glob.glob(os.path.join(demo_root, "*/")), |
| key=lambda p: int(os.path.basename(os.path.normpath(p))), |
| ) |
| return [d for d in dirs if glob.glob(os.path.join(d, "*.png"))] |
|
|
|
|
| def keyframe_paths_for_demo(seq_dir, num_keyframes=8): |
| seq = sorted( |
| glob.glob(os.path.join(seq_dir, "*.png")), |
| key=lambda x: int(os.path.splitext(os.path.basename(x))[0]), |
| ) |
| if not seq: |
| return [] |
| n = len(seq) |
| indices = np.linspace(0, n - 1, num=num_keyframes, dtype=int) |
| return [seq[i] for i in indices] |
|
|
|
|
| def collect_policy_keyframes(demo_root, num_keyframes=8, display_size=224): |
| transform = build_r3m_display_transform(display_size) |
| traj_keyframes = [] |
| for seq_dir in load_demo_dirs(demo_root): |
| paths = keyframe_paths_for_demo(seq_dir, num_keyframes) |
| if len(paths) != num_keyframes: |
| continue |
| frames = [] |
| for path in paths: |
| raw = np.array(Image.open(path).convert("RGB")) |
| tensor = transform(raw) |
| frames.append(tensor.numpy()) |
| traj_keyframes.append(np.stack(frames, axis=0)) |
| return np.array(traj_keyframes) |
|
|
|
|
| def save_cursor_previews(full_png_path, output_stem): |
| """Save small JPG rows + HTML viewer (works when IDE image preview fails).""" |
| im = Image.open(full_png_path).convert("RGB") |
| w, h = im.size |
| out_dir = os.path.dirname(os.path.abspath(full_png_path)) |
| rows_dir = os.path.join(out_dir, "policy_keyframes_rows") |
| os.makedirs(rows_dir, exist_ok=True) |
|
|
| num_demos = h // max(1, w // 8) |
| |
| |
| row_h = h // 35 if h >= 35 * 8 else h // max(1, int(h / (w / 8))) |
| num_demos = max(1, h // row_h) |
|
|
| rows_html = [] |
| for i in range(num_demos): |
| top = i * row_h |
| bottom = h if i >= num_demos - 1 else (i + 1) * row_h |
| row = im.crop((0, top, w, bottom)) |
| row = row.resize( |
| (640, max(1, int(640 * row.height / row.width))), Image.Resampling.LANCZOS |
| ) |
| fname = f"demo_{i:02d}.jpg" |
| row.save(os.path.join(rows_dir, fname), format="JPEG", quality=88, optimize=True) |
| rows_html.append( |
| f'<div class="row"><span class="label">demo {i}</span>' |
| f'<img src="policy_keyframes_rows/{fname}" width="640"></div>' |
| ) |
|
|
| html_path = f"{output_stem}_viewer.html" |
| with open(html_path, "w", encoding="utf-8") as f: |
| f.write( |
| "<!DOCTYPE html><html><head><meta charset=\"utf-8\">" |
| "<title>Policy Keyframes</title><style>" |
| "body{font-family:system-ui;margin:12px;background:#1a1a1a;color:#ddd}" |
| "h1{font-size:16px}.row{margin:6px 0;display:flex;align-items:center;gap:8px}" |
| ".label{width:56px;font-size:11px;color:#888;flex-shrink:0}img{border:1px solid #444}" |
| "</style></head><body>" |
| "<h1>Policy input keyframes — rows=demos, cols=k0→k7</h1>" |
| "<p style=\"font-size:12px;color:#888\">" |
| "在浏览器打开此 HTML 文件查看(Cursor 图片预览可能不支持远程大图)</p>" |
| + "\n".join(rows_html) |
| + "</body></html>" |
| ) |
| print(f"Saved HTML viewer to {html_path}") |
| print(f"Saved {num_demos} row previews under {rows_dir}/") |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument( |
| "--demo_root", |
| default="/home/lei/Documents/tong/irl4idm/multi-task-tcc-robosuite/experiments/datasets/mimicgen/train/lift", |
| ) |
| parser.add_argument("--num_keyframes", type=int, default=8) |
| parser.add_argument( |
| "--output", |
| default="./logs/policy_input_keyframes.png", |
| ) |
| parser.add_argument( |
| "--preview", |
| default=None, |
| help="Unused; kept for compatibility. Previews are auto-generated.", |
| ) |
| args = parser.parse_args() |
|
|
| sampled_images = collect_policy_keyframes( |
| args.demo_root, num_keyframes=args.num_keyframes |
| ) |
| os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) |
| save_keyframe_visualization(sampled_images, args.output) |
|
|
| output_stem, _ = os.path.splitext(args.output) |
| save_cursor_previews(args.output, output_stem) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|