0

My goal is read an video file and get all frames as using the function cv2.imread() on image file.

I have read the tutorial on https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html

and found a closely related post

Python - Extracting and Saving Video Frames

However I don't understand how vidcap.read() works. Is it only read the first frame? How can move forward in time. Is it possible to assign the start time and end time for frames we want to get?

Rikeijin
  • 135
  • 5

1 Answers1

0

cv2.vidcap() will read one frame at a time and needs to be called again to read subsequent frames. That's what the while loop in the related post is doing. Keep in mind that the first frame is discarded, so the first image that is saved will be of frame #2. I commented the code from the post you linked:

# this is the video capture object
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')

# this reads the first frame
success,image = vidcap.read()
count = 0
success = True

# so long as vidcap can read the current frame... 
while success:

  # ...read the next frame (this is now your current frame)
  success,image = vidcap.read()
  count += 1 # moved this to be accurate with my 'second frame' statement
  print('Read a new frame: ', success)

  # this is where you put your functionality (this just saves the frame)
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file

For setting start and end times, to the best of my knowledge you will need to get the frame rates of the video (i.e. 30 fps) and extrapolate what the frame number you want to start with is. So say you want to start at 10 sec, then you would use a conditional inside of, or alongside the while loop so that you can control the frame that you want. Same goes for the last frame. So if you have a 1min video and only want the middle thirty seconds:

fps   = 30 # there is an opencv function to determine this
start = 15 # seconds
end   = 45 # seconds

while success:
    success,image = vidcap.read()
    count += 1
    if count =< end and count >= start
        # do something 
Jello
  • 420
  • 6
  • 13