Getting specific frames from VideoCapture opencv in python

yusuf picture yusuf · Nov 4, 2015 · Viewed 26.5k times · Source

I have the following code, which continuously fetches all the frames from a video by using VideoCapture library in opencv in python:

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

But I want to grab a specific frame in a specific timestamp in the video.

How can I achieve this?

Answer

abhishek picture abhishek · Jul 14, 2016

You can use set() function of VideoCapture.

You can calculate total frames:

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

Here 7 is the prop-Id. You can find more here http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html

After that you can set the frame number, suppose i want to extract 100th frame

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