yusuf
yusuf

Reputation: 3781

Getting specific frames from VideoCapture opencv in python

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?

Upvotes: 19

Views: 52096

Answers (2)

Eric De Luna
Eric De Luna

Reputation: 81

this is my first post so please don't rip into me if I don't follow protocol completely. I just wanted to respond to June Wang just in case she didn't figure out how to set the number of frames to be extracted, or in case anyone else stumbles upon this thread with that question:

The solution is the good ol' for loop:

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

Upvotes: 8

Abhishek Sachan
Abhishek Sachan

Reputation: 995

You can use set() function of VideoCapture.

You can calculate total frames:

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

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(cv2.CAP_PROP_FRAME_COUNT, 100)
ret, frame = cap.read()
cv2.imwrite("path_where_to_save_image", frame)

Upvotes: 41

Related Questions