在製作影像和逐帧处理一些视觉化的专案,时常会使用到OpenCV做影片的读写。以下提供图片转影像、影像转影像的两个写法。
导入套件与影像方法
from pathlib import Pathimport tqdmimport cv2def set_camera(filename: str, width: int, height: int, fps: float = 30.0, fourcc: str = 'mp4v') -> cv2.VideoWriter: return cv2.VideoWriter( filename, fourcc=cv2.VideoWriter_fourcc(*fourcc), fps=fps, frameSize=(width, height) )
(1)批量影像转影片
batch_images = sorted(Path('path/to/batch/dir').glob('*.jpg'))video_output_path = 'video.mp4'camera = Nonefor ip in tqdm.tqdm(batch_images): frame = cv2.imread(ip.as_posix()) # process ... if camera is None: h, w, _ = frame.shape camera = set_camera(video_output_path, w, h) camera.write(frame)camera.release()
(2)影片转影片
video = cv2.VideoCapture('path/to/video.mp4')video_output_path = 'video.mp4'camera = Nonefor i in tqdm.trange(int(video.get(7))): _, frame = video.read() # process ... if camera is None: h, w, _ = frame.shape camera = set_camera(video_output_path, w, h) camera.write(frame)camera.release()