OpenCV如何实现视频与图像之间的互转

小编给大家分享一下OpenCV如何实现视频与图像之间的互转,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

一、视频转图像

由于连续视频相邻帧的图像相似度很高,这对于数据集来说并不是一件好的事情,所以可以隔帧取图像。在下面的示例中,我就是每隔10帧取一次。

Python 代码如下:

import cv2def video2images(Video_Dir):"""
    function: video to pictures
    author: AIJun
    date:2021/3/17
    """cap = cv2.VideoCapture(Video_Dir)c = 1  # 帧数起点index = 1  # 图片命名起点,如1.jpgif not cap.isOpened():print("Cannot open camera")exit()while True:# 逐帧捕获ret, frame = cap.read()# 如果正确读取帧,ret为Trueif not ret:print("Can't receive frame (stream end?). Exiting ...")breakif c % 10 == 0:cv2.imwrite('pictures/' + str(index) + '.jpg', frame)index += 1c += 1cv2.waitKey(1)# 按键停止if cv2.waitKey(1) == ord('q'):breakcap.release()Video_Dir = "D:\数据集\data3_16\WIN_20210316_17_46_54_Pro.mp4"video2images(Video_Dir)

二、图像合成视频

下面展示了,将连续的图片合成一条视频,视频的帧率为24。Python代码如下:

import globimport osimport cv2def images2video(image_dir, save_name):fps = 24fourcc = cv2.VideoWriter_fourcc('X','V','I','D')video_w = cv2.VideoWriter(save_name, fourcc, fps, (1920, 1080))# 扫描文件夹中所有jpg文件images = glob.glob(os.path.join(image_dir, "*.jpg"))for i in range(1, len(images)):# 选中名为"{}.jpg".format(1) = 1.jpgimage_name = os.path.join(image_dir, "{}.jpg".format(i))frame = cv2.imread(image_name)video_w.write(frame)video_w.release()image_dir = "D:\Project\VideoToImage\pictures"save_name = "test.avi"images2video(image_dir, save_name)

以上是“OpenCV如何实现视频与图像之间的互转”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!