#!/usr/bin/env python3 """Download the source YouTube videos and extract the RealEstate10K-Cap frames. Frames are written as //frame__.jpg (k = 1..num_frames) which is the layout TKCAM expects for --frame_dir. Frame k corresponds to timestamps_us[k-1], re10k_pose_w2c[k-1] and trajectory_12d[k]. Requirements: pip install yt-dlp opencv-python pyarrow Examples: python scripts/download_frames.py --data-dir data --out-dir frames --split test python scripts/download_frames.py --data-dir data --out-dir frames --ids 000000 000001 Some videos have been removed from YouTube since RealEstate10K was released; those clips are listed in /failed.json. """ import argparse import json import glob import os from collections import defaultdict from concurrent.futures import ThreadPoolExecutor import cv2 import pyarrow.parquet as pq def load_clips(data_dir, split, ids): files = sorted(glob.glob(os.path.join(data_dir, f"{split or '*'}-*.parquet"))) if not files: raise FileNotFoundError(f"No parquet files for split={split!r} in {data_dir}") cols = ["id", "re10k_clip_id", "youtube_url", "youtube_video_id", "timestamps_us"] clips = [] for f in files: clips.extend(pq.read_table(f, columns=cols).to_pylist()) if ids: wanted = set(ids) clips = [c for c in clips if c["id"] in wanted or c["re10k_clip_id"] in wanted] return clips def download_video(url, video_id, cache_dir, max_height): import yt_dlp existing = glob.glob(os.path.join(cache_dir, f"{video_id}.*")) if existing: return existing[0] opts = { "format": f"bestvideo[height<={max_height}][ext=mp4]/best[height<={max_height}]/best", "outtmpl": os.path.join(cache_dir, "%(id)s.%(ext)s"), "quiet": True, "noprogress": True, "no_warnings": True, } with yt_dlp.YoutubeDL(opts) as ydl: info = ydl.extract_info(url, download=True) return ydl.prepare_filename(info) def extract_frames(video_path, timestamps_us, out_dir, height): """Stream the video once and keep, for each timestamp, the decoded frame closest to it.""" cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise RuntimeError(f"cannot open {video_path}") targets_ms = [t / 1000.0 for t in timestamps_us] # OpenCV's CAP_PROP_POS_MSEC seek is not frame accurate, so walk the video # with grab() and only decode frames near the clip. best = [None] * len(targets_ms) # (|dt|, frame) i = 0 while i < len(targets_ms): if not cap.grab(): break pos_ms = cap.get(cv2.CAP_PROP_POS_MSEC) if pos_ms < targets_ms[0] - 100.0: continue ok, frame = cap.retrieve() if not ok: break # advance past targets that this frame is already later than (by more than the best match) while i < len(targets_ms): dt = abs(pos_ms - targets_ms[i]) if best[i] is None or dt < best[i][0]: best[i] = (dt, frame) if pos_ms >= targets_ms[i]: i += 1 continue break cap.release() os.makedirs(out_dir, exist_ok=True) written = 0 for k, (ts, b) in enumerate(zip(timestamps_us, best), start=1): if b is None: continue frame = b[1] if height and frame.shape[0] != height: width = round(frame.shape[1] * height / frame.shape[0]) frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) cv2.imwrite(os.path.join(out_dir, f"frame_{k:06d}_{ts:012d}.jpg"), frame, [cv2.IMWRITE_JPEG_QUALITY, 95]) written += 1 return written def process_video(video_id, clips, args): try: path = download_video(clips[0]["youtube_url"], video_id, args.video_cache, args.max_height) except Exception as e: return [(c["id"], f"download failed: {e}") for c in clips] failures = [] for c in clips: try: n = extract_frames(path, c["timestamps_us"], os.path.join(args.out_dir, c["re10k_clip_id"]), args.height) if n != len(c["timestamps_us"]): failures.append((c["id"], f"extracted {n}/{len(c['timestamps_us'])} frames")) except Exception as e: failures.append((c["id"], f"extract failed: {e}")) if not args.keep_videos: os.remove(path) return failures def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--data-dir", default="data", help="folder with the *.parquet files") parser.add_argument("--out-dir", required=True) parser.add_argument("--split", choices=["train", "val", "test"], default=None, help="default: all splits") parser.add_argument("--ids", nargs="*", help="dataset ids or re10k_clip_ids to fetch (default: all)") parser.add_argument("--video-cache", default=None, help="default: /_videos") parser.add_argument("--keep-videos", action="store_true") parser.add_argument("--height", type=int, default=360, help="output frame height (0 = native)") parser.add_argument("--max-height", type=int, default=720, help="max video resolution to download") parser.add_argument("--workers", type=int, default=4) args = parser.parse_args() args.video_cache = args.video_cache or os.path.join(args.out_dir, "_videos") os.makedirs(args.video_cache, exist_ok=True) by_video = defaultdict(list) for c in load_clips(args.data_dir, args.split, args.ids): if not os.path.isdir(os.path.join(args.out_dir, c["re10k_clip_id"])): by_video[c["youtube_video_id"]].append(c) print(f"{sum(map(len, by_video.values()))} clips from {len(by_video)} videos to fetch") failed = {} with ThreadPoolExecutor(args.workers) as pool: for fails in pool.map(lambda kv: process_video(kv[0], kv[1], args), by_video.items()): failed.update(dict(fails)) with open(os.path.join(args.out_dir, "failed.json"), "w") as f: json.dump(failed, f, indent=2) print(f"done; {len(failed)} clips failed (see failed.json)") if __name__ == "__main__": main()