import argparse import cv2 import numpy as np def main(): parser = argparse.ArgumentParser(description="Overlay mask video on original video.") parser.add_argument("--video", required=True, help="Input video path (mp4).") parser.add_argument("--mask", required=True, help="Mask video path (mkv, single channel).") parser.add_argument("--output", required=True, help="Output mp4 path.") parser.add_argument("--alpha", type=float, default=0.3, help="Mask overlay strength.") args = parser.parse_args() cap = cv2.VideoCapture(args.video) mask_cap = cv2.VideoCapture(args.mask) if not cap.isOpened(): raise RuntimeError(f"Failed to open video: {args.video}") if not mask_cap.isOpened(): raise RuntimeError(f"Failed to open mask video: {args.mask}") fps = cap.get(cv2.CAP_PROP_FPS) or 25.0 width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fourcc = cv2.VideoWriter_fourcc(*"mp4v") writer = cv2.VideoWriter(args.output, fourcc, fps, (width, height), isColor=True) frame_idx = 0 try: while True: ret, frame = cap.read() ret_mask, mask = mask_cap.read() if not ret or not ret_mask: break if mask.ndim == 3: mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) else: mask_gray = mask if mask_gray.shape[0] != height or mask_gray.shape[1] != width: mask_gray = cv2.resize(mask_gray, (width, height), interpolation=cv2.INTER_NEAREST) color = np.zeros_like(frame) color[:, :, 1] = mask_gray overlay = cv2.addWeighted(frame, 1.0 - args.alpha, color, args.alpha, 0) writer.write(overlay) frame_idx += 1 finally: cap.release() mask_cap.release() writer.release() print(f"Saved {frame_idx} frames to {args.output}") if __name__ == "__main__": main()