[Python OpenCV] 批量图片转影片、影片处理

在製作影像和逐帧处理一些视觉化的专案,时常会使用到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()

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章