Sachin Prabhu
Sachin Prabhu

Reputation: 152

Is there a way to show last frame in opencv-python?

I need to show the last frame of a video. I can calculate last frame number manually and run below code.

last_frame_num = duration_in_seconds * video_fps #manual entry

vs = cv2.VideoCapture('test.mp4')
vs.set(cv2.CAP_PROP_POS_FRAMES, last_frame_num)

while True:
    ret, frame = vs.read()
    if ret:
        cv2.imshow('last_frame', frame)
    if cv2.waitKey(0) == 27:
        break
vs.release()
cv2.destroyAllWindows()

The first line of code is manual entry.

Is there a way I can get the last frame number directly for any video?

Upvotes: 2

Views: 5371

Answers (1)

api55
api55

Reputation: 11420

Since you want the last frame of a video, you can use VideoCapture::get with the property CAP_PROP_FRAME_COUNT. This will give you the amount of frames in the video. You can try to assign it to your variable like this:

last_frame_num = vs.get(cv2.CAP_PROP_FRAME_COUNT)

In my opinion it should have a -1 as well, since CAP_PROP_POS_FRAMES takes a "0-based index of the frame to be decoded/captured next". However, good to see that it worked for you even without the -1.

Upvotes: 6

Related Questions