import abc from pathlib import Path from dodgeballtracker.typing import VideoFrame import cv2 def create_video_writer(video_cap: cv2.VideoCapture, output_filename: Path) -> cv2.VideoWriter: # grab the width, height, and fps of the frames in the video stream. frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = int(video_cap.get(cv2.CAP_PROP_FPS)) # initialize the FourCC and a video writer object fourcc = cv2.VideoWriter_fourcc(*'mp4v') writer = cv2.VideoWriter(str(output_filename.absolute()), fourcc, fps, (frame_width, frame_height)) return writer class VideoWriter(abc.ABC): @abc.abstractmethod def write_frame(self, frame: VideoFrame) -> None: pass @abc.abstractmethod def close(self) -> None: pass @abc.abstractmethod def wait(self) -> bool: pass class NoopVideoWriter(VideoWriter): def write_frame(self, frame: VideoFrame) -> None: pass def close(self) -> None: pass def wait(self) -> bool: return False class MP4VVideoWriter(VideoWriter): def __init__(self, video_writer: cv2.VideoWriter) -> None: self._video_writer = video_writer def write_frame(self, frame: VideoFrame) -> None: self._video_writer.write(frame) def close(self) -> None: self._video_writer.release() cv2.destroyAllWindows() def wait(self) -> bool: return False #cv2.waitKey(1) == ord("q") @classmethod def from_frame(cls, input_: Path, output: Path) -> VideoWriter: video_cap = cv2.VideoCapture(str(input_)) try: return cls(create_video_writer(video_cap, output)) finally: video_cap.release() class MP4VVideoWriterWithFrame(MP4VVideoWriter): def write_frame(self, frame: VideoFrame) -> None: super().write_frame(frame) cv2.imshow("Frame", frame) def wait(self) -> bool: return cv2.waitKey(1) == ord("q")