Ant
Ant

Reputation: 1143

How can I extract a frame from a video with cv2 at a specific time in microseconds?

I have videos I need to grab frames of and store as png images.
I need only frames from specific times.
These times are in microseconds.
How can I grab only these frames?

ret, frame = cap.read()
cv2.imshow("Video", frame)

cap = cv2.VideoCapture("video.mp4")
count = 0
while vidcap.isOpened():

if count == int(308608300 / 1000000):
    cv2.imwrite(os.path.join(path_output_dir, '%d.png') % count)

cv2.destroyAllWindows()

Upvotes: 1

Views: 3019

Answers (1)

RythonDev
RythonDev

Reputation: 442

This sounds kind of similar with what I'm working on. So for this code just change the number at 'frameRate'.

import cv2
vidcap = cv2.VideoCapture('video.mp4')
def getFrame(sec):
    vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
    hasFrames,image = vidcap.read()
    if hasFrames:
        cv2.imwrite("folder/"+str(sec)+" sec.png", image)     # save frame as PNG file
    return hasFrames
sec = 0
frameRate = 0.25#it will capture image in each 0.25 second
success = getFrame(sec)
while success:
    sec = sec + frameRate
    sec = round(sec, 2)
    success = getFrame(sec)

Upvotes: 3

Related Questions