Search code examples
pythonopencvvideotimecamera

OpenCV Python Video capture - can someone check my code


Here is my code. I wanted to know the frame rate of my webcam. For some reason, the cap.get(5) which gets the fps property does not work for live capture. So I tried to do a work around in order to calculate the number of frames that are taken in each loop. I used the time.time() function to get the time between each frame (using which I can calculate the number of frames in a second). I get the result as around 0.128, but my problem right now is cv2.waitKey(x). Even if I substitute 1 or 10 or 100 for x the result remains the same.

Yes, I know x is in milliseconds. But if I put x as 100, I should get 0.2 right? What's wrong here? Any help would be appreciated. Also if someone can help me out with calculating the fps I would be glad. PS. All this started because the videos I save using OpenCV always appear too fast ie fast forwarded..

Note : If I put x as 1000, then I get 2.128.

import numpy as np
import cv2
import time

cap = cv2.VideoCapture(0)
#print cap.get(5)

# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'XVID') 
out = cv2.VideoWriter('output1.avi',fourcc, 10, (640,480))

while(cap.isOpened()):
    start = time.time()
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,1) 
       
        # write the flipped frame
        out.write(frame)        

        cv2.imshow('frame',frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break


    end = (time.time() - start)
    print end

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

Solution

  • I'd try aggrigating them as suggested here: OpenCV: VideoCapture::get(CV_CAP_PROP_FPS) returns 0 FPS

    Something like:

    import numpy as np
    import cv2
    import time
    
    cap = cv2.VideoCapture(0)
    #print cap.get(5)
    
    # Define the codec and create VideoWriter object
    fourcc = cv2.cv.CV_FOURCC(*'XVID')
    
    num_frames = 0
    
    start = time.time()
    while(cap.isOpened()):
    
        ret, frame = cap.read()
        if num_frames < 500:
            frame = cv2.flip(frame,1)
            num_frames = num_frames + 1;
        else:
            break
    
    
    total_time = (time.time() - start)
    fps = (num_frames / total_time)
    print str(num_frames) + ' frames in ' + str(total_time) + ' seconds = ' + str(fps) + ' fps'
    
    # Release everything if job is finished
    cap.release()
    cv2.destroyAllWindows()