#!/usr/bin/env python3 # -*- coding: utf-8 -*- import subprocess from pathlib import Path from typing import Optional, Sequence import cv2 import numpy as np import pandas as pd from tqdm import tqdm # ========================= # Parameters # ========================= DATAMAKER_DIR = Path(__file__).resolve().parent PROJECT_ROOT = DATAMAKER_DIR.parent RAW_IR_DIR = PROJECT_ROOT / "raw" / "videos" / "ir" RAW_VI_DIR = PROJECT_ROOT / "raw" / "videos" / "vi" OUTPUT_DIR = DATAMAKER_DIR / "01_align" VIDEO_IDS = [f"{idx:02d}" for idx in range(1, 15)] MAX_GAP_SECONDS = 0.08 SAVE_EXCEL = True FOURCC = "mp4v" OVERWRITE = True # ========================= def get_frame_timestamps(video_path: Path) -> list[float]: cmd = [ "ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "frame=pkt_pts_time,best_effort_timestamp_time", "-of", "csv=p=0", str(video_path), ] try: result = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True, ) except subprocess.CalledProcessError as exc: raise RuntimeError(f"ffprobe failed for {video_path}: {exc.stderr}") from exc timestamps: list[float] = [] for line in result.stdout.splitlines(): for value in line.split(","): value = value.strip() if not value or value == "N/A": continue try: timestamps.append(float(value)) break except ValueError: continue if not timestamps: raise RuntimeError(f"No frame timestamps found in {video_path}") return timestamps def build_monotone_map( base_ts: Sequence[float], src_ts: Sequence[float], max_gap: float, ) -> list[int]: if not base_ts or not src_ts: raise ValueError("Timestamp lists must not be empty.") mapping: list[int] = [] src_idx = 0 for timestamp in base_ts: while ( src_idx + 1 < len(src_ts) and abs(src_ts[src_idx + 1] - timestamp) < abs(src_ts[src_idx] - timestamp) ): src_idx += 1 mapping.append(src_idx if abs(src_ts[src_idx] - timestamp) <= max_gap else -1) return mapping def make_black_frame(cap: cv2.VideoCapture) -> np.ndarray: height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) return np.zeros((height, width, 3), dtype=np.uint8) def make_writers( cap_base: cv2.VideoCapture, cap_src: cv2.VideoCapture, out_base: Path, out_src: Path, ) -> tuple[cv2.VideoWriter, cv2.VideoWriter]: fps = cap_base.get(cv2.CAP_PROP_FPS) base_size = ( int(cap_base.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap_base.get(cv2.CAP_PROP_FRAME_HEIGHT)), ) src_size = ( int(cap_src.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap_src.get(cv2.CAP_PROP_FRAME_HEIGHT)), ) fourcc = cv2.VideoWriter_fourcc(*FOURCC) out_base.parent.mkdir(parents=True, exist_ok=True) out_src.parent.mkdir(parents=True, exist_ok=True) writer_base = cv2.VideoWriter(str(out_base), fourcc, fps, base_size) writer_src = cv2.VideoWriter(str(out_src), fourcc, fps, src_size) if not writer_base.isOpened() or not writer_src.isOpened(): raise IOError(f"Failed to open output writers: {out_base}, {out_src}") return writer_base, writer_src def align_videos( ir_path: Path, vi_path: Path, out_ir: Path, out_vi: Path, excel_path: Optional[Path], ) -> None: if not ir_path.exists() or not vi_path.exists(): raise FileNotFoundError(f"Missing input pair: {ir_path}, {vi_path}") if not OVERWRITE and (out_ir.exists() or out_vi.exists()): raise FileExistsError(f"Output exists and OVERWRITE=False: {out_ir}, {out_vi}") ir_ts = get_frame_timestamps(ir_path) vi_ts = get_frame_timestamps(vi_path) if len(ir_ts) <= len(vi_ts): base_ts, src_ts = ir_ts, vi_ts base_path, src_path = ir_path, vi_path out_base, out_src = out_ir, out_vi base_label, src_label = "IR", "VI" else: base_ts, src_ts = vi_ts, ir_ts base_path, src_path = vi_path, ir_path out_base, out_src = out_vi, out_ir base_label, src_label = "VI", "IR" src_indices = build_monotone_map(base_ts, src_ts, MAX_GAP_SECONDS) cap_base = cv2.VideoCapture(str(base_path)) cap_src = cv2.VideoCapture(str(src_path)) if not cap_base.isOpened() or not cap_src.isOpened(): raise IOError(f"Failed to open videos: {base_path}, {src_path}") writer_base, writer_src = make_writers(cap_base, cap_src, out_base, out_src) ok_src, frame_src = cap_src.read() src_idx_prev = 0 if ok_src else -1 black_src = make_black_frame(cap_src) for base_idx in tqdm( range(len(base_ts)), desc=f"Align {ir_path.stem}", unit="frame", position=1, leave=False, ): ok_base, frame_base = cap_base.read() if not ok_base: break mapped_idx = src_indices[base_idx] if mapped_idx < 0: frame_to_write = black_src else: while src_idx_prev < mapped_idx: ok_src, frame_src = cap_src.read() src_idx_prev += 1 frame_to_write = frame_src if ok_src and frame_src is not None else black_src writer_base.write(frame_base) writer_src.write(frame_to_write) cap_base.release() cap_src.release() writer_base.release() writer_src.release() if SAVE_EXCEL and excel_path is not None: excel_path.parent.mkdir(parents=True, exist_ok=True) matched_src_ts = [src_ts[idx] if idx >= 0 else None for idx in src_indices] diffs = [ base_time - src_time if src_time is not None else None for base_time, src_time in zip(base_ts, matched_src_ts) ] pd.DataFrame( { "Base_Idx": range(len(base_ts)), f"{base_label}_ts(s)": base_ts, f"{src_label}_nearest_ts(s)": matched_src_ts, "DeltaT(s)": diffs, } ).to_excel(excel_path, index=False) def main() -> None: with tqdm( total=len(VIDEO_IDS), desc="Total align", unit="video", position=0, ) as progress: for video_id in VIDEO_IDS: progress.set_postfix(video=video_id) out_dir = OUTPUT_DIR / video_id align_videos( ir_path=RAW_IR_DIR / f"{video_id}.mp4", vi_path=RAW_VI_DIR / f"{video_id}.mp4", out_ir=out_dir / "ir.mp4", out_vi=out_dir / "vi.mp4", excel_path=out_dir / "timestamp.xlsx" if SAVE_EXCEL else None, ) tqdm.write(f"Aligned {video_id} -> {out_dir}") progress.update(1) if __name__ == "__main__": main()