How to always get latest frame from OpenCV VideoCapture in Python
When working with OpenCV video capture, but when you only occasionally use images, you will get older images from the capture buffer.
This code example solves this issue by running a separate capture thread that continually saves images to a temporary buffer.
Therefore, you can always get the latest image from the buffer. The code is based on our basic example How to take a webcam picture using OpenCV in Python
video_capture = cv2.VideoCapture(0)
video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
if not video_capture.isOpened():
raise Exception("Could not open video device")
class TakeCameraLatestPictureThread(threading.Thread):
def __init__(self, camera):
self.camera = camera
self.frame = None
super().__init__()
# Start thread
self.start()
def run(self):
while True:
ret, self.frame = self.camera.read()
latest_picture = TakeCameraLatestPictureThread(video_capture)
Usage example:
# Convert latest image to the correct colorspace
rgb_img = cv2.cvtColor(latest_picture.frame, cv2.COLOR_BGR2RGB)
# Show
plt.imshow(rgb_img)