| |
| """Extract representative frames from MP4 demonstrations for manual inspection.""" |
|
|
| import argparse |
| import json |
| import os |
| from pathlib import Path |
| from typing import List, Optional |
|
|
| import mediapy as media |
| import numpy as np |
|
|
|
|
| def parse_fractions(fractions): |
| values = [] |
| for f in fractions: |
| value = float(f) |
| if not 0.0 <= value <= 1.0: |
| raise ValueError(f"Fraction {value} must be in [0, 1].") |
| values.append(value) |
| return values |
|
|
|
|
| def extract_frames(video_path: Path, fractions, output_dir: Path, video_root: Optional[Path]): |
| frames = media.read_video(video_path) |
| if len(frames) == 0: |
| print(f"[WARN] {video_path}: empty video") |
| return 0 |
| frame_indices = sorted(set(int(round(frac * (len(frames) - 1))) for frac in fractions)) |
| base = video_path.stem |
| if video_root is not None: |
| try: |
| rel_dir = video_path.parent.relative_to(video_root) |
| except ValueError: |
| rel_dir = Path() |
| else: |
| rel_dir = Path() |
| save_dir = output_dir / rel_dir / base |
| save_dir.mkdir(parents=True, exist_ok=True) |
| saved = 0 |
| for idx in frame_indices: |
| frame = frames[idx] |
| out_path = save_dir / f"frame_{idx:04d}.png" |
| media.write_image(out_path, frame) |
| saved += 1 |
| return saved |
|
|
|
|
| def iter_videos_from_preview(preview_path: Path) -> List[Path]: |
| videos: List[Path] = [] |
| with preview_path.open("r", encoding="utf-8") as fh: |
| for line in fh: |
| if not line.strip(): |
| continue |
| record = json.loads(line) |
| if record.get("instruction") is not None: |
| continue |
| h5_path = Path(record["path"]) |
| video_name = h5_path.name.replace("data_", "demo_").replace(".hdf5", ".mp4") |
| video_path = h5_path.with_name(video_name) |
| videos.append(video_path) |
| return videos |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Sample frames from MP4 videos.") |
| parser.add_argument("--video-dir", help="Directory containing demo_*.mp4 files.") |
| parser.add_argument( |
| "--pattern", |
| default="demo_*.mp4", |
| help="Glob relative to --video-dir for selecting videos (default: demo_*.mp4).", |
| ) |
| parser.add_argument( |
| "--frames", |
| nargs="+", |
| default=["0.1", "0.5", "0.9"], |
| help="Normalized positions (0-1) from which to sample frames.", |
| ) |
| parser.add_argument("--output", required=True, help="Directory to store extracted frame images.") |
| parser.add_argument("--max-videos", type=int, help="Optional cap on number of videos to process.") |
| parser.add_argument( |
| "--preview-json", |
| type=Path, |
| help="JSONL preview file (from update_instructions script). Only videos with null instruction will be processed.", |
| ) |
| parser.add_argument( |
| "--dataset-root", |
| help="Root directory containing the dataset (used to preserve relative structure when --preview-json is set).", |
| ) |
| args = parser.parse_args() |
|
|
| output_dir = Path(args.output).expanduser().resolve() |
| output_dir.mkdir(parents=True, exist_ok=True) |
| fractions = parse_fractions(args.frames) |
|
|
| videos: List[Path] |
| video_root: Optional[Path] |
| if args.preview_json: |
| preview_path = Path(args.preview_json).expanduser().resolve() |
| videos = iter_videos_from_preview(preview_path) |
| if args.dataset_root: |
| video_root = Path(args.dataset_root).expanduser().resolve() |
| else: |
| |
| parents = {vp.parent for vp in videos} |
| parent_paths = [str(p) for p in parents] |
| video_root = Path(os.path.commonpath(parent_paths)) if parent_paths else None |
| else: |
| if not args.video_dir: |
| raise ValueError("--video-dir is required when --preview-json is not provided.") |
| video_root = Path(args.video_dir).expanduser().resolve() |
| videos = sorted(video_root.glob(args.pattern)) |
|
|
| if args.max_videos is not None: |
| videos = videos[: args.max_videos] |
| print(f"Found {len(videos)} videos to process.") |
| total_frames = 0 |
| for vp in videos: |
| if not vp.exists(): |
| print(f"[WARN] Missing video {vp}") |
| continue |
| total_frames += extract_frames(vp, fractions, output_dir, video_root) |
| print(f"Saved {total_frames} frames into {output_dir}.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|