File size: 4,794 Bytes
9f30907 | 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import math
import subprocess
from pathlib import Path
from tqdm import tqdm
# =========================
# Parameters
# =========================
DATAMAKER_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = DATAMAKER_DIR.parent
INPUT_DIR = DATAMAKER_DIR / "02_warp"
OUTPUT_DIR = PROJECT_ROOT / "dataset"
VIDEO_IDS = [f"{idx:02d}" for idx in range(1, 15)]
WINDOW_LEN_SECONDS = 5
STRIDE_SECONDS = 5
KEEP_AUDIO = False
TOLERANCE_SECONDS = 0.02
OVERWRITE = True
# =========================
def probe(video_path: Path) -> tuple[float, int]:
cmd = [
"ffprobe",
"-v",
"error",
"-count_frames",
"-select_streams",
"v:0",
"-show_entries",
"stream=nb_read_frames,nb_frames,duration:format=duration",
"-print_format",
"json",
str(video_path),
]
raw = subprocess.check_output(cmd, stderr=subprocess.DEVNULL, text=True)
info = json.loads(raw)
stream = info["streams"][0]
duration = float(stream.get("duration") or info.get("format", {}).get("duration"))
frames_raw = stream.get("nb_read_frames") or stream.get("nb_frames")
if frames_raw is None:
raise RuntimeError(f"Could not read frame count: {video_path}")
return duration, int(frames_raw)
def segment_count(duration: float) -> int:
if duration < WINDOW_LEN_SECONDS:
return 0
return math.floor((duration - WINDOW_LEN_SECONDS) / STRIDE_SECONDS) + 1
def pad_seconds(seconds: int) -> str:
return f"{seconds:04d}"
def clip_video(src: Path, dst: Path, start: int, duration: int) -> None:
dst.parent.mkdir(parents=True, exist_ok=True)
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-nostats"]
cmd.append("-y" if OVERWRITE else "-n")
cmd += [
"-ss",
str(start),
"-i",
str(src),
"-t",
str(duration),
"-c:v",
"copy",
]
cmd += ["-c:a", "copy"] if KEEP_AUDIO else ["-an"]
cmd.append(str(dst))
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
def collect_valid_pairs() -> list[tuple[str, Path, Path, float]]:
valid_pairs: list[tuple[str, Path, Path, float]] = []
for video_id in tqdm(VIDEO_IDS, desc="Probe videos", unit="video"):
ir_path = INPUT_DIR / video_id / "ir.mp4"
vi_path = INPUT_DIR / video_id / "vi.mp4"
if not ir_path.exists() or not vi_path.exists():
raise FileNotFoundError(f"Missing input pair: {ir_path}, {vi_path}")
ir_duration, ir_frames = probe(ir_path)
vi_duration, vi_frames = probe(vi_path)
if abs(ir_duration - vi_duration) >= TOLERANCE_SECONDS:
raise ValueError(
f"{video_id}: duration mismatch "
f"ir={ir_duration:.3f}s vi={vi_duration:.3f}s"
)
if ir_frames != vi_frames:
raise ValueError(
f"{video_id}: frame mismatch ir={ir_frames} vi={vi_frames}"
)
valid_pairs.append((video_id, ir_path, vi_path, ir_duration))
return valid_pairs
def main() -> None:
valid_pairs = collect_valid_pairs()
total_clips = sum(2 * segment_count(duration) for _, _, _, duration in valid_pairs)
if total_clips == 0:
tqdm.write("No valid 5-second clips found.")
return
(OUTPUT_DIR / "ir").mkdir(parents=True, exist_ok=True)
(OUTPUT_DIR / "vi").mkdir(parents=True, exist_ok=True)
with tqdm(
total=len(valid_pairs),
desc="Total split",
unit="video",
position=0,
) as video_progress, tqdm(
total=total_clips,
desc="Split clips",
unit="clip",
position=1,
leave=False,
) as clip_progress:
for video_id, ir_path, vi_path, duration in valid_pairs:
video_progress.set_postfix(video=video_id)
start = 0
while start + WINDOW_LEN_SECONDS <= duration:
end = start + WINDOW_LEN_SECONDS
name = f"{video_id}_{pad_seconds(start)}_{pad_seconds(end)}.mp4"
clip_video(ir_path, OUTPUT_DIR / "ir" / name, start, WINDOW_LEN_SECONDS)
clip_progress.update(1)
clip_video(vi_path, OUTPUT_DIR / "vi" / name, start, WINDOW_LEN_SECONDS)
clip_progress.update(1)
start += STRIDE_SECONDS
if start < duration:
skipped = duration - start
tqdm.write(
f"{video_id}: skipped tail {skipped:.2f}s "
f"(< {WINDOW_LEN_SECONDS}s)"
)
video_progress.update(1)
tqdm.write(f"Dataset clips written to {OUTPUT_DIR}")
if __name__ == "__main__":
main()
|