Is there a way to get a specific frame using VideoCapture()
method?
My current code is:
import numpy as np
import cv2
cap = cv2.VideoCaptur
From the documentation of the VideoCaptureProperties (docs) is possible to see that the way to set the frame in the VideoCapture is:
frame = 30
cap.set(cv2.CAP_PROP_POS_FRAMES, frame)
Notice that you don't have to pass to the function frame - 1
because, as the documentation says, the flag CAP_PROP_POS_FRAMES
rapresent the "0-based index of the frame to be decoded/captured next".
Concluding a full example where i want to read a frame at each second is:
import cv2
cap = cv2.VideoCapture('video.avi')
# Get the frames per second
fps = cap.get(cv2.CAP_PROP_FPS)
# Get the total numer of frames in the video.
frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
frame_number = 0
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number) # optional
success, image = cap.read()
while success and frame_number <= frame_count:
# do stuff
frame_number += fps
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
success, image = cap.read()
In the documentation linked above is possible to see that the way to set a specific time in the VideoCapture is:
milliseconds = 1000
cap.set(cv2.CAP_PROP_POS_MSEC, milliseconds)
And like before a full example that read a frame each second che be achieved in this way:
import cv2
cap = cv2.VideoCapture('video.avi')
# Get the frames per second
fps = cap.get(cv2.CAP_PROP_FPS)
# Get the total numer of frames in the video.
frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
# Calculate the duration of the video in seconds
duration = frame_count / fps
second = 0
cap.set(cv2.CAP_PROP_POS_MSEC, second * 1000) # optional
success, image = cap.read()
while success and second <= duration:
# do stuff
second += 1
cap.set(cv2.CAP_PROP_POS_MSEC, second * 1000)
success, image = cap.read()