python: use opencv to realize image to video conversion, video to image conversion

   The OpenCV environment needs to be installed, and the video-to-picture code is as follows:

import cv2
def Video2Pic():
    videoPath = r"video/yolov5+deep+best2.mp4"  # 读取视频路径
    imgPath = r"picture/yolov5+deep+best2/"  # 保存图片路径,路径最后加/斜杠

    cap = cv2.VideoCapture(videoPath)
    suc = cap.isOpened()  # 是否成功打开
    frame_count = 0
    while suc:
        frame_count += 1
        suc, frame = cap.read()
        cv2.imwrite(imgPath + str(frame_count).zfill(4)+'.jpg', frame)#转化图片的格式,可改成png
        cv2.waitKey(1)
    cap.release()
    print("视频转图片结束!")
if __name__ == '__main__':
     Video2Pic()

    It seems that there will be a warning, but it will not affect the normal conversion.

  Next is the image to video code:

import cv2
import os
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')  # 设置输出视频为mp4格式
# cap_fps是帧率,根据自己需求设置帧率
cap_fps = 30

# size要和图片的size一样,但是通过img.shape得到图像的参数是(height,width,channel),
# 可以实现在图片文件夹下查看图片属性,获得图片的分辨率
size = (1920,1080)#size(width,height)
# 设置输出视频的参数,如果是灰度图,可以加上 isColor = 0 这个参数
# video = cv2.VideoWriter('results/result.avi',fourcc, cap_fps, size, isColor=0)
video = cv2.VideoWriter('result.mp4', fourcc, cap_fps, size)#设置保存视频的名称和路径,默认在根目录下

path = './he_chen_video/'#设置图片文件夹的路径,末尾加/
file_lst = os.listdir(path)
for filename in file_lst:
    img = cv2.imread(path + filename)
    video.write(img)
video.release()

Guess you like

Origin blog.csdn.net/weixin_39357271/article/details/124413807