What is the correct approach to always use the latest camera frame in OpenCV

45 Views Asked by At

I am trying to take stills from a webcam and do some processing on the images

I am using Python 3.10.9 and opencv-python==4.9.0.80

This is pretty much how I set up a USB webcam

camera = cv2.VideoCapture(0) 
camera.set(cv2.CAP_PROP_FRAME_WIDTH, frame_width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_height)

And this is how I take photos

camera_status, photo = camera.read()

I noticed though that quite often the picture that is taken is not the latest one, browsing online I found out that as a workaround you have to clear the camera buffer by trying to read frames. So as a workaround I tried reading 4 frames first to clear the buffer, and then only process the 5th one. This works, it just significantly slows down the photo capture speed

# 1. Clear camera buffer
try:
    for _ in range(4):
        camera.read()
except Exception as e:
    raise RuntimeError(f'Encountered error trying to clear camera buffer: {e}')

My webcam is around 24FPS, I tried setting up a thread that continuously reads 16 frames per second. This likewise helps with making sure that every still is the latest frame, but the capture duration has alot more variance now

Meaning some photos take 0.009 seconds, and other 0.5 seconds.

Is there a cleaner, or some standard and accepted approach to ensuring that getting a still from the camera stream is always the freshest in OpenCV?

Thanks

0

There are 0 best solutions below