I’m trying to capture an image from my Raspberry Pi camera module using OpenCV. The code runs without errors, but the frame I get is completely black.
When I use rpicam-still -o Desktop/image.jpg
I am able to get a still picture from the camera. However, when I run this code that I found on the internet, I only get a completely black frame. I’m not sure where I got it from, but it’s a generic code that just tries to use OpenCV.
The code:
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
print(frame.max(), frame.mean())
cv.imshow('frame', frame)
cv.imwrite('frame.png', frame)
if cv.waitKey(1) == ord('q'):
break
cap.release()
cv.destroyAllWindows()
Update:
Right now, this is what my code looks like after the modifications you suggested. However, the result remains the same, as I still get a black frame. At this point, I’ve modified pretty much everything that was suggested, but I didn’t set an exposure time in this code because I tried it earlier, and it didn’t seem to improve anything. If anyone thinks I should try setting the exposure time again, please let me know, and also if any more information is needed.
Also, I’m running this in Thonny IDE, and I’m using a Raspberry Pi 3 (with Raspberry Pi OS 64-bit) with a RaspiCam module. I already checked the OpenCV installation, and everything seems to be fine, but I’ll include the versions of Python and OpenCV that I’m using:
$ pip show opencv-python
Name: opencv-python
Version: 4.10.0.84
Summary: Wrapper package for OpenCV python bindings.
Home-page: https://github.com/opencv/opencv-python
Author:
Author-email:
License: Apache 2.0
$ python3 --version
Python 3.11.2
(This is my first time posting here, and English is not my native language, so let me know if you have any questions about my writing or the data I provided.)
Lucas Flores Hinrichsen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
17