0

I believe there is a possible error with this code because it saves more images than it should when I calculate (fps * seconds). It also saves a NULL image at the end. I feel like this is the most basic code to save images and I'm not sure what the error could be.

Also, I'd like an option to specify at which fps rate I'd take the images. The fps I would like the use the most is 1 fps. I couldn't find a feature in opencv that allows us to specify this, so I was considering taking the approach of somehow saving a frame at each second. Another approach could be saving all the frames, but iterating through and using the frame at each second. I'm fairly new at these concepts. Are these approaches good, and how should I begin coding them? I'm not sure where to begin.

def extractFrames():

vidcap = cv2.VideoCapture('video.AVI')  
success,image = vidcap.read()
count = 0;
while success:
    success,image = vidcap.read()
    cv2.imwrite("%d.jpg" % count, image)
    count += 1
Jaden
  • 265
  • 3
  • 16

1 Answers1

0

This should do what you request:

import time,cv2
import numpy as np
def extractFrames(n):
    """
    extract image from a live video frame at n fps, 
    if the n is smaller than the fps of the camera
    """
    vidcap = cv2.VideoCapture('video.AVI')  
    now = time.time()
    success,image = vidcap.read()
    real_fps = 1.0/(time.time()-now);

    if n > real_fps:
        print('real fps is smaller than what you want , change to less than '+real_fps)
        return

    while success:
        now = time.time()
        success,image = vidcap.read()
        cv2.imwrite("%d.jpg" % count, image)
        ch = 0xFF & cv2.waitKey(1)
        if ch == 27:
            break
        time.sleep((1.0/n) - (time.time() - now));


    cv2.destroyAllWindows()
extractFrames(1)

P.S:

I recommend using library like Pygame for event loops and drawing instead of Opencv's function

Yasin Yousif
  • 969
  • 7
  • 23