Python:視頻拆分成一幀一幀的圖片

簡(jiǎn)介:在AI的數(shù)據(jù)集采集視頻相關(guān)的測(cè)試中,可能需要將視頻拆分成一幀一幀的圖片進(jìn)行保存,然后在從關(guān)鍵幀中定位問(wèn)題或標(biāo)注等。我們可以通過(guò)cv庫(kù)對(duì)視頻進(jìn)行分成一幀幀的圖片進(jìn)行保存,相當(dāng)于圖片轉(zhuǎn)視頻的反向操作。

相關(guān)教程:

Python:用ffmpeg多圖轉(zhuǎn)視頻

源碼

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參數(shù)表示間隔多少幀截取一張圖片
    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方法參數(shù)按順序?qū)?yīng)下表 CV_CAP_PROP_FRAME_COUNT
    frames_num = cap.get(7)

    video_duration = get_video_duration(video_file)
    print("拆分視頻成圖片數(shù)目為:", 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則,實(shí)際產(chǎn)生圖片數(shù)目為:

372 / 50 = 7張。

執(zhí)行效果:

圖片

附獲取視頻各種參數(shù)介紹:如上面的案例cap.get(7)即獲取第八個(gè)CV_CAP_PROP_FRAME_COUNT #視頻總幀數(shù) , 以此類推。

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  #視頻總幀數(shù)
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)
圖片

微信公眾號(hào):玩轉(zhuǎn)測(cè)試開(kāi)發(fā)
歡迎關(guān)注,共同進(jìn)步,謝謝!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容