Search code examples
pythonopencvv4l2

Weird outcomes using V4L2, python, on raspberry pi 3


Weird coding outcome which isn't making much sense. I am trying to capture from a raspberry pi camera using the V4L2 driver as I need to use cv2 for image processing. I am using python to write the code.

The weirdness revolves around capturing images using cv2. when I type in the following commands

import cv2
from matplotlib import pyplot

camera = cv2.VideoCapture(0)
grab,frame = camera.read()
pyplot.imshow(frame)

I am able to grab a frame and display it using matplotlib. When I grab a second frame

grab,frame2 = camera.read()
pyplot.imshow(frame2)

The code will grab a second frame and display it perfectly fine.

However when I try to use an existing variable like frame or frame2 the camera will not grab a new frame and just print the prior frame.

I tried to clear the variable by typing

frame = []
grab,frame = camera.read()
pyplot.imshow(frame)    

but this didn't fix the issue, still printing the prior frame.


Solution

  • I think you are "suffering from buffering"!

    When OpenCV reads a frame, it tends to gather a few, I think it is 5 frames or so, or there may be some algorithm that determines available memory or something similar.

    Anyway, the answer is to read a few more frames to clear the buffer and then it will acquire some fresh frames.