#!/usr/bin/env python3 """Generate a first-frame grid per subdir under ICLR/. For each subdir (task), each episode contributes a row; columns are the video views (e.g. 37149196_left/right, 11845904_left/right). Each cell is the first frame of that episode's mp4, labeled. One PNG per subdir saved into ICLR/. """ import subprocess, sys from pathlib import Path from PIL import Image, ImageDraw, ImageFont ROOT = Path("/home/jimin/droid/collected_datasets/rlwrld_datasets_jonghoon/ICLR") THUMB_W = 320 # per-cell frame width; height scales to aspect PAD = 6 # gap between cells LABEL_H = 20 # label strip height per cell HEADER_H = 34 # column-header strip ROWLABEL_W = 70 # left strip for episode id def first_frame(mp4: Path) -> Image.Image | None: """Extract first frame of an mp4 as a PIL image via ffmpeg (stdout png).""" try: out = subprocess.run( ["ffmpeg", "-nostdin", "-loglevel", "error", "-i", str(mp4), "-frames:v", "1", "-f", "image2pipe", "-vcodec", "png", "pipe:1"], capture_output=True, check=True).stdout if not out: return None from io import BytesIO return Image.open(BytesIO(out)).convert("RGB") except subprocess.CalledProcessError as e: print(f" ! ffmpeg failed on {mp4.name}: {e.stderr.decode()[:200]}") return None def font(size=14): for p in ["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"]: if Path(p).exists(): return ImageFont.truetype(p, size) return ImageFont.load_default() def build_grid(subdir: Path): episodes = sorted([d for d in subdir.iterdir() if d.is_dir() and d.name.isdigit()]) if not episodes: print(f" (no episodes in {subdir.name})") return # Determine the union of view names (mp4 stems) across episodes, stable order. views: list[str] = [] for ep in episodes: vdir = ep / "recorded_videos" if not vdir.is_dir(): continue for mp4 in sorted(vdir.glob("*.mp4")): if mp4.stem not in views: views.append(mp4.stem) views = sorted(views) if not views: print(f" (no mp4s in {subdir.name})") return print(f" {subdir.name}: {len(episodes)} episodes x {len(views)} views") # Extract all cells first to learn the thumb height (from first good frame). cells: dict[tuple[int, int], Image.Image] = {} thumb_h = None for r, ep in enumerate(episodes): for c, view in enumerate(views): mp4 = ep / "recorded_videos" / f"{view}.mp4" if not mp4.exists(): continue img = first_frame(mp4) if img is None: continue w, h = img.size th = round(THUMB_W * h / w) img = img.resize((THUMB_W, th)) if thumb_h is None: thumb_h = th cells[(r, c)] = img if thumb_h is None: print(f" ! could not extract any frame for {subdir.name}") return cell_w = THUMB_W cell_h = thumb_h + LABEL_H ncols, nrows = len(views), len(episodes) W = ROWLABEL_W + ncols * cell_w + (ncols + 1) * PAD H = HEADER_H + nrows * cell_h + (nrows + 1) * PAD canvas = Image.new("RGB", (W, H), (24, 24, 28)) draw = ImageDraw.Draw(canvas) f_hdr, f_lbl, f_row = font(15), font(12), font(14) # Column headers for c, view in enumerate(views): x = ROWLABEL_W + PAD + c * (cell_w + PAD) draw.text((x + 4, 8), view, fill=(230, 230, 235), font=f_hdr) for r, ep in enumerate(episodes): y0 = HEADER_H + PAD + r * (cell_h + PAD) draw.text((6, y0 + thumb_h // 2), ep.name, fill=(255, 210, 90), font=f_row) for c, view in enumerate(views): x0 = ROWLABEL_W + PAD + c * (cell_w + PAD) img = cells.get((r, c)) if img is None: draw.rectangle([x0, y0, x0 + cell_w, y0 + thumb_h], fill=(50, 40, 40)) draw.text((x0 + 8, y0 + thumb_h // 2 - 6), "missing", fill=(200, 120, 120), font=f_lbl) else: canvas.paste(img, (x0, y0)) draw.text((x0 + 3, y0 + thumb_h + 3), f"{ep.name}/{view}", fill=(180, 180, 190), font=f_lbl) out = ROOT / f"first_frame_grid_{subdir.name}.png" canvas.save(out) print(f" -> saved {out} ({W}x{H})") def main(): subdirs = sorted([d for d in ROOT.iterdir() if d.is_dir() and not d.name.startswith("_")]) print(f"Found {len(subdirs)} subdirs: {[d.name for d in subdirs]}") for sd in subdirs: build_grid(sd) if __name__ == "__main__": main()