File size: 2,358 Bytes
f15a766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Batch GT|pred side-by-side videos for every prediction window of a checkpoint.

Mirrors the preds/<episode>/start<NNNN>.npz layout: writes one combined mp4 per
window to <ckpt-dir>/<out-name>/<episode>/start<NNNN>.mp4 (GT left + label, pred right).
"""
import argparse
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw

DATA = Path("/workspace/gnn_data/hanoi_0420_balanced_5fps")
W, H, SEP = 320, 192, 4


def label(arr, text, xy=(5, 5)):
    im = Image.fromarray(arr)
    d = ImageDraw.Draw(im)
    tw = len(text) * 6 + 8
    d.rectangle([xy[0] - 3, xy[1] - 3, xy[0] + tw, xy[1] + 13], fill=(0, 0, 0))
    d.text(xy, text, fill=(255, 255, 255))
    return np.asarray(im)


def load_gt(episode, frame_ids):
    out = []
    for fid in frame_ids:
        im = Image.open(DATA / episode / "side" / "rgb" / f"frame_{int(fid):06d}.png").convert("RGB").resize((W, H), Image.BILINEAR)
        out.append(np.asarray(im, dtype=np.uint8))
    return np.stack(out)


def write_mp4(path, frames, fps):
    try:
        import mediapy as media
        media.write_video(str(path), frames, fps=fps)
    except Exception:
        import imageio.v2 as imageio
        imageio.mimwrite(str(path), frames, fps=fps, macro_block_size=None)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ckpt-dir", type=Path, required=True)
    ap.add_argument("--out-name", default="viz_gt_vs_pred")
    ap.add_argument("--fps", type=int, default=5)
    cli = ap.parse_args()

    preds = cli.ckpt_dir / "preds"
    out_root = cli.ckpt_dir / cli.out_name
    npzs = sorted(preds.glob("*/start*.npz"))
    print(f"{len(npzs)} windows -> {out_root}")
    sep = np.full((H, SEP, 3), 255, np.uint8)
    for i, npz in enumerate(npzs, 1):
        episode = npz.parent.name
        d = np.load(npz)
        pred, fids = d["pred"], d["frame_ids"]
        gt = load_gt(episode, fids)
        frames = np.stack([
            np.concatenate([label(gt[k], "GT"), sep, label(pred[k], "PRED")], axis=1)
            for k in range(len(pred))
        ])
        od = out_root / episode
        od.mkdir(parents=True, exist_ok=True)
        write_mp4(od / f"{npz.stem}.mp4", frames, cli.fps)
        if i % 15 == 0 or i == len(npzs):
            print(f"  {i}/{len(npzs)}", flush=True)
    print("done:", out_root)


if __name__ == "__main__":
    main()