I am using OpenCV2 to take some timelapse photos with a webcam. I want to extract the most recent view seen by the webcam. I try to accomplish this like so.
import cv2
a = cv2.VideoCapture(1)
ret, frame = a.read()
#The following garbage just shows the image and waits for a key press
#Put something in front of the webcam and then press a key
cv2.imshow('a',frame); cv2.waitKey(0); cv2.destroyAllWindows(); [cv2.waitKey(25) for i in range(10)]
#Since something was placed in front of the webcam we naively expect
#to see it when we read in the next image. We would be wrong.
ret, frame = a.read()
cv2.imshow('a',frame); cv2.waitKey(0); cv2.destroyAllWindows(); [cv2.waitKey(25) for i in range(10)]
Except that the image placed in front of the webcam does not show. It's almost as if there's some kind of buffer...
So I purge that buffer, like so:
import cv2
a = cv2.VideoCapture(1)
ret, frame = a.read()
#Place something in front of the webcam and then press a key
cv2.imshow('a',frame); cv2.waitKey(0); cv2.destroyAllWindows(); [cv2.waitKey(25) for i in range(10)]
#Purge the buffer
for i in range(10): #Annoyingly arbitrary constant
a.grab()
#Get the next frame. Joy!
ret, frame = a.read()
cv2.imshow('a',frame); cv2.waitKey(0); cv2.destroyAllWindows(); [cv2.waitKey(25) for i in range(10)]
Now this works, but it's annoyingly unscientific and slow. Is there a way to ask specifically for only the most recent image in the buffer? Or, baring that, a better way to purge the buffer?