I try to use OpenCV in Python 3 on a Raspberry Pi Zero to capture a video frame from a USB camera identified as /dev/video0
. Here is my code:
import cv2
...
cam = cv2.VideoCapture(0)
if cam.isOpened():
print("Camera successfully opened")
else:
print("Camera could not be opened")
while True:
success, image = cam.read()
print("success in taking image? ", success)
if success and not image.empty():
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
// further code to be excecuted to process the image
else:
print("problem capturing image")
The output is
Camera successfully opened
success in taking image? False
problem capturing image
success in taking image? False
problem capturing image
success in taking image? False
problem capturing image
...
It will never take an image successfully. It worked once (success = True
) for a single iteration the very first time I executed my script but since then it is not working any more. So my first assumption was that the camera is broken. But if I use motion to access the camera, it works flawlessly. So the camera is connected correctly.
Any clue on what I am doing wrong?
OK I got the problem solved. It was a concurrency issue. I had put a cam.release()
in a finally:
block but in the wrong one so always right before I was trying to take a picture accidentally this finally:
block was excecuted and the cam was released BEFORE actually trying to take a picture