【Python】从视频文件中每秒抽取固定数量图像保存为图片

num表示每秒抽取几帧图像保存成图片。

import cv2
import os

def newDir(fileDir):
    fileDir = fileDir.strip()
    if not os.path.exists(fileDir):
        os.makedirs(fileDir)
    else:
        print(fileDir+'already exists!!!')

def video2Images(video, imgPerSec):
    if not os.path.exists(video):
        print('video file dost not exist!!!')
        return

    path, fileName = os.path.split(video)
    folder = fileName.split('.')[0]
    savePath = os.path.join(path, folder)
    newDir(savePath)

    ov = cv2.VideoCapture(video)
    retval = ov.isOpened()
    frames = ov.get(cv2.CAP_PROP_FPS)
    print('video have {} frames'.format(ov.get(cv2.CAP_PROP_FRAME_COUNT)))
    count = int(frames//imgPerSec)
    print(count)
    k = 0
    f = 0
    while 1:
        retval, img = ov.read()
        if retval:
            cv2.imshow('video', img)
            cv2.waitKey(25)
        else:
            cv2.destroyAllWindows()
            break
        k += 1

        if k == count:
            k = 0
            f += 1
            print('>>>>>>>>>save image<<<<<<<<<<<')
            filename = os.path.join(savePath, "{}_{}".format(folder, f))+'.jpg'
            print(filename)
            #cv2.imwrite(filename, img)#路径有中文的话,imwrite会失败
            cv2.imencode('.jpg', img)[1].tofile(filename)
            cv2.waitKey(1)

    ov.release()

if __name__ == '__main__':
    video = "D:\\数据集\\Cam.mp4"
    num = 1
    video2Images(video, num)

 

你可能感兴趣的:(opencv,Python)