Python:视频拆分成一帧一帧的图片

简介:在AI的数据集采集视频相关的测试中,可能需要将视频拆分成一帧一帧的图片进行保存,然后在从关键帧中定位问题或标注等。我们可以通过cv库对视频进行分成一帧帧的图片进行保存,相当于图片转视频的反向操作。

相关教程:

Python:用ffmpeg多图转视频

源码

import cv2
import argparse
import os


def get_video_duration(filename):
    cap = cv2.VideoCapture(filename)
    if cap.isOpened():
        rate = cap.get(5)
        frame_num = cap.get(7)
        duration = frame_num / rate
        return duration
    return -1


def parse_args(video_file, picture_path, default):
    parser = argparse.ArgumentParser(description='Process pic')
    parser.add_argument('--input', help='video to process', dest='input', default=None, type=str)
    parser.add_argument('--output', help='pic to store', dest='output', default=None, type=str)

    # default参数表示间隔多少帧截取一张图片
    parser.add_argument('--skip_frame', dest='skip_frame', help='skip number of video', default=default, type=int)

    args = parser.parse_args(['--input', video_file, '--output', picture_path])
    return args


def process_video(i_video, o_video, num):
    cap = cv2.VideoCapture(i_video)
    num_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    expand_name = '.jpg'
    if not cap.isOpened():
        print("Please check the path.")
    cnt = 0
    count = 0
    while 1:
        ret, frame = cap.read()
        cnt += 1
        if cnt % num == 0:
            count += 1
            cv2.imwrite(os.path.join(o_video, str(count) + expand_name), frame)

        if not ret:
            break


if __name__ == '__main__':
    video_file = r"C:\xxxxx\betterPro\videos\duck.mp4"
    picture_path = r"C:\xxxxx\betterPro\picture"
    frame = 50
    cap = cv2.VideoCapture(video_file)

    # get方法参数按顺序对应下表 CV_CAP_PROP_FRAME_COUNT
    frames_num = cap.get(7)

    video_duration = get_video_duration(video_file)
    print("拆分视频成图片数目为:", int(frames_num / frame))

    args = parse_args(video_file, picture_path, default=frame)
    if not os.path.exists(args.output):
        os.makedirs(args.output)
    process_video(args.input, args.output, args.skip_frame)

例如原视频12秒,帧率50/秒。总帧为372则,实际产生图片数目为:

372 / 50 = 7张。

执行效果:

图片

附获取视频各种参数介绍:如上面的案例cap.get(7)即获取第八个CV_CAP_PROP_FRAME_COUNT #视频总帧数 , 以此类推。

CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds or video capture timestamp.
CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film.
CV_CAP_PROP_FRAME_WIDTH    #视频帧宽度
CV_CAP_PROP_FRAME_HEIGHT    #视频帧高度
CV_CAP_PROP_FPS            #视频帧速率
CV_CAP_PROP_FOURCC 4-character code of codec.
CV_CAP_PROP_FRAME_COUNT  #视频总帧数
CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .
CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.
CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).
CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).
CV_CAP_PROP_HUE Hue of the image (only for cameras).
CV_CAP_PROP_GAIN Gain of the image (only for cameras).
CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
CV_CAP_PROP_WHITE_BALANCE_U The U value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
CV_CAP_PROP_WHITE_BALANCE_V The V value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
CV_CAP_PROP_ISO_SPEED The ISO speed of the camera (note: only supported by DC1394 v 2.x backend currently)
CV_CAP_PROP_BUFFERSIZE Amount of frames stored in internal buffer memory (note: only supported by DC1394 v 2.x backend currently)
图片

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

你可能感兴趣的:(Python:视频拆分成一帧一帧的图片)