视频抽帧及将图片合成视频

整理一篇将视频抽帧成图片,然后在将图片合成视频文章!!!听起来就很无聊,但是还是记录以下吧,万一下次在干这种事我就能直接用啦!

1.视频抽帧

'''
功能:将视频逐帧抽取,在文件夹中保存为图片,可设置间隔帧数进行抽取,可设置图片名
'''

import cv2


def video2images(Video_Dir):
    cap = cv2.VideoCapture(Video_Dir)
    c = 1  # 帧数起点
    index = 1  # 图片命名起点,如1.jpg

    if not cap.isOpened():
        print("Cannot open camera")
        exit()

    while True:
        # 逐帧捕获
        ret, frame = cap.read()
        # 如果正确读取帧,ret为True
        if not ret:
            print("Can't receive frame.")
            break
        # 设置每5帧取一次图片,若想逐帧抽取图片,可设置c % 1 == 0
        if c % 5 == 0:
            # 图片存放路径,即图片文件夹路径  路径不能出现中文
            cv2.imwrite("C:/Users/Desktop/class_actions/images/" + str(index) + '.jpg', frame)
            index += 1
        c += 1
        cv2.waitKey(1)
        # 按键停止
        if cv2.waitKey(1) == ord('q'):
            break
    cap.release()


# 视频存放路径 路径不能出现中文
Video_Dir = r"C:\Users\Desktop\class_actions\videos\1.mp4"
video2images(Video_Dir)

2.图片合成视频

import cv2

# 其它格式的图片也可以
img_array = []
#range:图片第1张到304
for item in range(1,304):
  #图片路径 
    filename = 'C:/Users/Desktop/classActions/after/'+str(item)+'.jpg'
    print(filename)
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width, height)
    img_array.append(img)

# avi:视频类型,mp4也可以
# cv2.VideoWriter_fourcc(*'DIVX'):编码格式
# 30:视频帧率
# size:视频中图片大小

#合成视频存放路径
out = cv2.VideoWriter(r'C:\Users\Desktop\classActions\dajia.mp4', cv2.VideoWriter_fourcc(*'DIVX'), 30, size)
for i in range(len(img_array)):
    out.write(img_array[i])
out.release()

猜你喜欢

转载自blog.csdn.net/JulyLH/article/details/127876074