#!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path import cv2 import numpy as np from tqdm import tqdm # ========================= # Parameters # ========================= DATAMAKER_DIR = Path(__file__).resolve().parent INPUT_DIR = DATAMAKER_DIR / "02_warp" OUTPUT_DIR = DATAMAKER_DIR / "03_ckboard" VIDEO_IDS = [f"{idx:02d}" for idx in range(1, 15)] BLOCK_SIZE = 50 FOURCC = "mp4v" OVERWRITE = True # ========================= def create_checkerboard_mask(height: int, width: int, block_size: int) -> np.ndarray: x = np.arange(width) y = np.arange(height) x_grid, y_grid = np.meshgrid(x, y) mask = np.mod(x_grid // block_size + y_grid // block_size, 2) return mask.astype(bool) def fuse_checkerboard( ir_frame: np.ndarray, vi_frame: np.ndarray, block_size: int, ) -> np.ndarray: if len(ir_frame.shape) == 2: ir_frame = cv2.cvtColor(ir_frame, cv2.COLOR_GRAY2BGR) if ir_frame.shape[:2] != vi_frame.shape[:2]: raise ValueError( f"Frame sizes differ: IR={ir_frame.shape[:2]}, VI={vi_frame.shape[:2]}" ) height, width = ir_frame.shape[:2] mask = create_checkerboard_mask(height, width, block_size) mask_3d = np.stack([mask] * 3, axis=2) return np.where(mask_3d, ir_frame, vi_frame) def make_checkerboard(ir_path: Path, vi_path: Path, out_path: 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_path.exists(): raise FileExistsError(f"Output exists and OVERWRITE=False: {out_path}") cap_ir = cv2.VideoCapture(str(ir_path)) cap_vi = cv2.VideoCapture(str(vi_path)) if not cap_ir.isOpened() or not cap_vi.isOpened(): raise IOError(f"Failed to open videos: {ir_path}, {vi_path}") width = int(cap_ir.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap_ir.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap_ir.get(cv2.CAP_PROP_FPS) total_frames = min( int(cap_ir.get(cv2.CAP_PROP_FRAME_COUNT)), int(cap_vi.get(cv2.CAP_PROP_FRAME_COUNT)), ) out_path.parent.mkdir(parents=True, exist_ok=True) writer = cv2.VideoWriter( str(out_path), cv2.VideoWriter_fourcc(*FOURCC), fps, (width, height), ) if not writer.isOpened(): raise IOError(f"Failed to open output writer: {out_path}") for _ in tqdm( range(total_frames), desc=f"Checkerboard {ir_path.parent.name}", unit="frame", position=1, leave=False, ): ok_ir, frame_ir = cap_ir.read() ok_vi, frame_vi = cap_vi.read() if not ok_ir or not ok_vi: break writer.write(fuse_checkerboard(frame_ir, frame_vi, BLOCK_SIZE)) cap_ir.release() cap_vi.release() writer.release() def main() -> None: with tqdm( total=len(VIDEO_IDS), desc="Total checkerboard", unit="video", position=0, ) as progress: for video_id in VIDEO_IDS: progress.set_postfix(video=video_id) out_path = OUTPUT_DIR / f"{video_id}.mp4" make_checkerboard( ir_path=INPUT_DIR / video_id / "ir.mp4", vi_path=INPUT_DIR / video_id / "vi.mp4", out_path=out_path, ) tqdm.write(f"Checkerboard {video_id} -> {out_path}") progress.update(1) if __name__ == "__main__": main()