簡體   English   中英

在 python 中從 VideoCapture opencv 獲取特定幀

[英]Getting specific frames from VideoCapture opencv in python

我有以下代碼,它通過在 python 中的 opencv 中使用 VideoCapture 庫從視頻中連續獲取所有幀:

import cv2

def frame_capture:
        cap = cv2.VideoCapture("video.mp4")
        while not cap.isOpened():
                cap = cv2.VideoCapture("video.mp4")
                cv2.waitKey(1000)
                print "Wait for the header"

        pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
        while True:
                flag, frame = cap.read()
                if flag:
                        # The frame is ready and already captured
                        cv2.imshow('video', frame)
                        pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
                        print str(pos_frame)+" frames"
                else:
                        # The next frame is not ready, so we try to read it again
                        cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
                        print "frame is not ready"
                        # It is better to wait for a while for the next frame to be ready
                        cv2.waitKey(1000)

                if cv2.waitKey(10) == 27:
                        break
                if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
                        # If the number of captured frames is equal to the total number of frames,
                        # we stop
                        break

但我想在視頻的特定時間戳中抓取特定幀。

我怎樣才能做到這一點?

您可以使用 VideoCapture 的 set() 函數。

您可以計算總幀數:

cap = cv2.VideoCapture("video.mp4")
total_frames = cap.get(7)

這里 7 是 prop-Id。 你可以在這里找到更多http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html

之后你可以設置幀數,假設我想提取第 100 幀

cap.set(1, 100)
ret, frame = cap.read()
cv2.imwrite("path_where_to_save_image", frame)

這是我的第一篇文章,所以如果我不完全遵守協議,請不要攻擊我。 我只是想回復 June Wang 以防萬一她不知道如何設置要提取的幀數,或者以防其他人偶然發現這個問題的線程:

解決方案是好的 ol' for 循環:

    vid = cv2.VideoCapture(video_path)
    for i in range(start_frame, how_many_frames_you_want):
        vid.set(1, i)
        ret, still = vid.read()
        cv2.imwrite(f'{video_path}_frame{i}.jpg', still)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM