| |
| """ |
| 从 frames 目录 + CSV(index,value,critic,done)生成左右拼接视频: |
| 左侧当前帧;右侧与 output_2_with_plots 风格一致:顶栏 |
| 「Critic: … | Value: … | Done: …」(四位小数),其下三个纵向子图 |
| (Value 绿 0–50、Critic 红 0–50、Done 蓝 0–1),折线 + 圆点,当前帧圆点更大。 |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import re |
| from pathlib import Path |
|
|
| import matplotlib |
|
|
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import numpy as np |
| from matplotlib.gridspec import GridSpec |
| from PIL import Image |
|
|
|
|
| def natural_sort_key(p: Path) -> tuple[int, ...]: |
| m = re.search(r"(\d+)", p.stem) |
| return (int(m.group(1)),) if m else (0,) |
|
|
|
|
| def load_frames_dir(frames_dir: Path) -> list[Path]: |
| paths = sorted(frames_dir.glob("frame_*.png"), key=natural_sort_key) |
| if not paths: |
| paths = sorted(frames_dir.glob("*.png"), key=natural_sort_key) |
| if not paths: |
| raise FileNotFoundError(f"No PNG frames under {frames_dir}") |
| return paths |
|
|
|
|
| def load_metrics_csv(csv_path: Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]: |
| """返回 value, critic, done — 每行对应一个 frame(按 CSV 行顺序)。""" |
| with csv_path.open(newline="", encoding="utf-8") as f: |
| reader = csv.DictReader(f) |
| if not reader.fieldnames: |
| raise ValueError(f"Empty CSV: {csv_path}") |
| rows = list(reader) |
|
|
| def col(row: dict, name: str) -> str: |
| for k, v in row.items(): |
| if k and k.strip().lower() == name.lower(): |
| return v |
| raise KeyError(f"Missing column {name!r} in row {row}") |
|
|
| values: list[float] = [] |
| critics: list[float] = [] |
| dones: list[float] = [] |
|
|
| for row in rows: |
| row = {k.strip(): v for k, v in row.items() if k is not None} |
| values.append(float(col(row, "value"))) |
| critics.append(float(col(row, "critic"))) |
| dones.append(float(col(row, "done"))) |
|
|
| return ( |
| np.asarray(values, dtype=np.float64), |
| np.asarray(critics, dtype=np.float64), |
| np.asarray(dones, dtype=np.float64), |
| ) |
|
|
|
|
| def align_metrics_to_frame_count( |
| n_frames: int, |
| value: np.ndarray, |
| critic: np.ndarray, |
| done: np.ndarray, |
| ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: |
| """将 CSV 中的序列对齐到 n_frames 条(不足则重复最后一行,过多则截断)。""" |
| if len(value) == n_frames: |
| return value, critic, done |
| if len(value) > n_frames: |
| return value[:n_frames], critic[:n_frames], done[:n_frames] |
| pad = n_frames - len(value) |
| value = np.concatenate([value, np.full(pad, value[-1])]) |
| critic = np.concatenate([critic, np.full(pad, critic[-1])]) |
| done = np.concatenate([done, np.full(pad, done[-1])]) |
| return value, critic, done |
|
|
|
|
| def _plot_metric_subplot( |
| ax, |
| x: np.ndarray, |
| y: np.ndarray, |
| line_color: str, |
| ylabel: str, |
| ylabel_color: str, |
| ylim: tuple[float, float], |
| *, |
| show_xlabel: bool, |
| ) -> None: |
| """折线 + 小圆点;最后一个点更大(当前帧)。x/y 长度一致。""" |
| ax.set_facecolor("#f0f0f0") |
| if len(x) > 1: |
| ax.plot(x, y, color=line_color, linewidth=2.0, zorder=2, solid_capstyle="round") |
| ax.scatter( |
| x[:-1], |
| y[:-1], |
| s=45, |
| color=line_color, |
| zorder=3, |
| edgecolors="white", |
| linewidths=0.9, |
| ) |
| ax.scatter( |
| x[-1], |
| y[-1], |
| s=140, |
| color=line_color, |
| zorder=4, |
| edgecolors="white", |
| linewidths=1.2, |
| ) |
| ax.set_ylim(ylim[0], ylim[1]) |
| ax.set_ylabel(ylabel, fontsize=10, color=ylabel_color) |
| ax.tick_params(axis="y", labelcolor=ylabel_color) |
| ax.grid(True, alpha=0.35, color="#bbbbbb") |
| if show_xlabel: |
| ax.set_xlabel("frame index", fontsize=10) |
|
|
|
|
| def render_frame( |
| img_path: Path, |
| t: int, |
| n_frames: int, |
| value: np.ndarray, |
| critic: np.ndarray, |
| done: np.ndarray, |
| figsize: tuple[float, float], |
| dpi: int, |
| ) -> np.ndarray: |
| """返回 RGB uint8 拼接图 (H, W, 3),右侧布局对齐 output_2_with_plots 风格。""" |
| img = np.asarray(Image.open(img_path).convert("RGB")) |
|
|
| fig = plt.figure(figsize=figsize, dpi=dpi) |
| gs = GridSpec( |
| 4, |
| 2, |
| figure=fig, |
| width_ratios=[1.0, 1.15], |
| height_ratios=[0.14, 1.0, 1.0, 1.0], |
| wspace=0.08, |
| hspace=0.30, |
| left=0.04, |
| right=0.98, |
| top=0.94, |
| bottom=0.08, |
| ) |
|
|
| ax_l = fig.add_subplot(gs[1:4, 0]) |
| ax_l.imshow(img) |
| ax_l.set_axis_off() |
|
|
| ax_hdr = fig.add_subplot(gs[0, 1]) |
| ax_hdr.set_facecolor("#f0f0f0") |
| ax_hdr.axis("off") |
| header = ( |
| f"Critic: {float(critic[t]):.4f} | " |
| f"Value: {float(value[t]):.4f} | " |
| f"Done: {float(done[t]):.4f}" |
| ) |
| ax_hdr.text(0.5, 0.45, header, ha="center", va="center", fontsize=10, color="black") |
|
|
| ax_v = fig.add_subplot(gs[1, 1]) |
| ax_c = fig.add_subplot(gs[2, 1], sharex=ax_v) |
| ax_d = fig.add_subplot(gs[3, 1], sharex=ax_v) |
|
|
| xs = np.arange(0, t + 1, dtype=np.float64) |
| x_hi = float(max(n_frames - 1, 1)) |
| for ax in (ax_v, ax_c, ax_d): |
| ax.set_xlim(0.0, x_hi) |
|
|
| _plot_metric_subplot( |
| ax_v, |
| xs, |
| value[: t + 1], |
| "#2ca02c", |
| "Value", |
| "#2ca02c", |
| (0.0, 50.0), |
| show_xlabel=False, |
| ) |
| _plot_metric_subplot( |
| ax_c, |
| xs, |
| critic[: t + 1], |
| "#d62728", |
| "Critic", |
| "#d62728", |
| (0.0, 50.0), |
| show_xlabel=False, |
| ) |
| _plot_metric_subplot( |
| ax_d, |
| xs, |
| done[: t + 1], |
| "#1f77b4", |
| "Done", |
| "black", |
| (0.0, 1.0), |
| show_xlabel=True, |
| ) |
|
|
| plt.setp(ax_v.get_xticklabels(), visible=False) |
| plt.setp(ax_c.get_xticklabels(), visible=False) |
|
|
| fig.patch.set_facecolor("white") |
| fig.canvas.draw() |
| w_px, h_px = fig.canvas.get_width_height() |
| buf = np.asarray(fig.canvas.buffer_rgba()) |
| buf = buf.reshape(h_px, w_px, 4)[..., :3].copy() |
| plt.close(fig) |
| |
| h, w = buf.shape[:2] |
| nh = (h + 15) // 16 * 16 |
| nw = (w + 15) // 16 * 16 |
| if nh != h or nw != w: |
| buf = np.pad(buf, ((0, nh - h), (0, nw - w), (0, 0)), mode="edge") |
| return buf |
|
|
|
|
| def build_video( |
| frames_dir: Path, |
| csv_path: Path, |
| out_mp4: Path, |
| fps: float = 8.0, |
| figsize: tuple[float, float] = (12.0, 5.5), |
| dpi: int = 120, |
| ) -> Path: |
| frame_paths = load_frames_dir(frames_dir) |
| n = len(frame_paths) |
|
|
| value, critic, done = load_metrics_csv(csv_path) |
| value, critic, done = align_metrics_to_frame_count(n, value, critic, done) |
|
|
| out_mp4.parent.mkdir(parents=True, exist_ok=True) |
| try: |
| import imageio.v2 as imageio |
|
|
| writer = imageio.get_writer(out_mp4, fps=fps, codec="libx264", quality=8) |
| for t in range(n): |
| rgb = render_frame( |
| frame_paths[t], |
| t, |
| n, |
| value, |
| critic, |
| done, |
| figsize=figsize, |
| dpi=dpi, |
| ) |
| writer.append_data(rgb) |
| writer.close() |
| except Exception: |
| import cv2 |
|
|
| fourcc = cv2.VideoWriter_fourcc(*"mp4v") |
| first = render_frame(frame_paths[0], 0, n, value, critic, done, figsize, dpi) |
| h, w = first.shape[:2] |
| vw = cv2.VideoWriter(str(out_mp4), fourcc, fps, (w, h)) |
| for t in range(n): |
| rgb = render_frame(frame_paths[t], t, n, value, critic, done, figsize, dpi) |
| vw.write(cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)) |
| vw.release() |
|
|
| print(f"[ok] wrote {out_mp4} ({n} frames @ {fps} fps)") |
| return out_mp4 |
|
|
|
|
| def main(): |
| p = argparse.ArgumentParser(description="Frames + metrics -> side-by-side video (frame | plots).") |
| p.add_argument( |
| "--frames", |
| type=Path, |
| default=Path("/scratch1/home/zhicao/VLAC/evo_vlac/examples/images/test"), |
| help="Directory with PNG frames (frame_*.png or numbered *.png, natural sort)", |
| ) |
| p.add_argument( |
| "--csv", |
| type=Path, |
| default=Path("/scratch1/home/zhicao/VLAC/2.txt"), |
| help="CSV with header: index,value,critic,done", |
| ) |
| p.add_argument( |
| "-o", |
| "--output", |
| type=Path, |
| default=Path("/scratch1/home/zhicao/VLAC/output_test_with_plots.mp4"), |
| help="Output mp4 path", |
| ) |
| p.add_argument( |
| "--fps", |
| type=float, |
| default=5.0, |
| help="Output video frame rate (lower = slower playback)", |
| ) |
| p.add_argument("--dpi", type=int, default=120) |
| args = p.parse_args() |
|
|
| build_video(args.frames, args.csv, args.output, fps=args.fps, dpi=args.dpi) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|