1

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()
Ant
  • 933
  • 2
  • 17
  • 33
  • Any reason not to just use `ffmpeg`? – Mark Setchell Apr 28 '20 at 16:49
  • try this answer https://stackoverflow.com/a/27486167/3210415 – Nicolae Apr 28 '20 at 19:08
  • "Any reason not to just use ffmpeg" I need it to happen in Python because it is reading from txt files and putting things in different folders, and creating folders. – Ant Apr 28 '20 at 22:42
  • Thank you for this answer @Nicolae. When I do `success,image = vidcap.read()` and `getvalue = vidcap.get(0)` I see `getvalue` returns a new value each time. I'm a bit lost about what this value is and how to pinpoint microseconds of exact frames. – Ant Apr 28 '20 at 23:43

1 Answers1

3

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)
RyanPython
  • 412
  • 1
  • 5
  • 14