欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python opencv 批量将视频转化为图片

程序员文章站 2022-07-14 19:20:40
...

单个的视频转换图片参看:

python opencv 把视频转为图片

 

对于多个视频,采用多线程处理方法

video_path为待转换视频的路径,pic_path为输出图像的路径,输出的图像统一保存在pic_path下面与相应视频名相同的文件夹下面。

代码如下:

# coding=utf-8
import cv2
import os
import threading
from threading import Lock, Thread

video_path = "./video/"
pic_path = "./pic/"
filelist = os.listdir(video_path)  


def video2pic(filename):
    # print(filename)
    cnt = 0
    dnt = 0
    if os.path.exists(pic_path + str(filename)):
        pass
    else:
        os.mkdir(pic_path + str(filename))
    cap = cv2.VideoCapture(video_path + str(filename))  # 读入视频
    while True:
        # get a frame
        ret, image = cap.read()
        if image is None:
            break
        # show a frame

        w = image.shape[1]
        h = image.shape[0]
        if (cnt % 20) == 0:
            cv2.imencode('.jpg', image)[1].tofile(pic_path + str(filename) + '/' + str(dnt) + '.jpg')
            print(pic_path + str(filename) + '/' + str(dnt) + '.jpg')
            dnt = dnt + 1
        cnt = cnt + 1
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()


if __name__ == '__main__':
    for filename in filelist:
        threading.Thread(target=video2pic, args=(filename, )).start()

python opencv 批量将视频转化为图片