从python中的VideoCapture opencv获取特定帧

yus*_*suf 8 python opencv video-capture

我有以下代码,它通过在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
Run Code Online (Sandbox Code Playgroud)

但我想在视频中的特定时间戳中抓取特定帧.

我怎样才能做到这一点?

abh*_*hek 17

您可以使用VideoCapture的set()函数.

您可以计算总帧数:

cap = cv2.VideoCapture("video.mp4")
total_frames = cap.get(7)
Run Code Online (Sandbox Code Playgroud)

这里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)
Run Code Online (Sandbox Code Playgroud)

  • 太好了!我会指定`7`是``CV_CAP_PROP_FRAME_COUNT的序数值和`1`是CV_CAP_PROP_POS_FRAMES`的`序价值 - 你在这里做还等什么,你实际上是移动"帧读者"来第100帧的偏移,然后你读取"下一个",即第101帧 (4认同)
  • 有没有办法设置要提取的帧数? (2认同)

Eri*_*una 5

这是我的第一篇文章,所以如果我不完全遵守协议,请不要攻击我。我只是想回复 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)
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到SO。解释你的代码如何回答问题总是一件好事。 (2认同)