OpenCV批量将文件夹下的视频隔一定帧数取一张图像并保存

OpenCV对视频处理,以下为Python代码:
默认每隔10帧取一张图像,每张图像命名为 {视频名}_{数字编号}.jpg


import numpy as np
import cv2
import glob
import time
import os

def process_video(VIDEO_PATH,count):
    head, tail = os.path.split(VIDEO_PATH)

    print("Video file name : {}".format(tail))
    common_file_name = tail.split('.')[-2]
    cv2.namedWindow('gauge', cv2.WINDOW_NORMAL)
    # cv2.namedWindow('gauge',cv2.WINDOW_AUTOSIZE)
    vs = cv2.VideoCapture(VIDEO_PATH)
    time.sleep(2.0)

    idx = count
    while True:
        _, src = vs.read()
        if src is None:
            print("The video is processed over !")
            break
        start = cv2.getTickCount()
      ####  用于设置隔多少帧保存一张图像,以下为每10张保存一张
        if idx%10==0:
            # 逆时针旋转90度
            src = cv2.transpose(src)

            # transpose->flip,90度
            src = cv2.flip(src, 1)

            # # 180度
            # src = cv2.flip(src, -1)
            # # 270度
            # src = cv2.flip(src, 0)

            image_filename = ("%06d" % idx) + ".jpg"
            image_name = '{}_{}'.format(common_file_name, image_filename)
            image_file = os.path.join(OUTPUT_DIR, image_name)
            cv2.imwrite(image_file, src)

            # show the frame
            cv2.imshow("gauge", src)

        fps_time = (cv2.getTickCount() - start) / cv2.getTickFrequency()
        key = cv2.waitKey(1)
        if key == ord("q") or key == 0xFF:
            break
        idx = idx + 1

    # do a bit of cleanup
    cv2.destroyAllWindows()
    return idx

if __name__ == "__main__":

    ### 输出图像保存路径
    OUTPUT_DIR = "/home/sdb/GaugeVideo_Imgs"
    ### 视频所在路径
    video_mp4 = glob.glob('/home/sdb/GaugeVideo/*.mp4')
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)

    ### 用于设置起始图像编号
    img_num =0
    for num, video_file in enumerate(video_mp4):
        print("Start processing {}th video!".format(num))
        video_img_count = process_video(video_file,img_num)
        img_num = video_img_count




你可能感兴趣的:(Python,计算机视觉,OpenCV)