How to use OpenCV to call the Raspberry Pi Camera v2.1 on the Rock3C?

Currently, I can use Cheese to call my Raspberry Pi Camera v2, but OpenCV cannot call /dev/video0.

The following command is also executable.

gst-launch-1.0 v4l2src device=/dev/video0 io-mode=4 ! videoconvert ! video/x-raw,format=NV12,width=1920,height=1080 ! jpegenc ! multifilesink location=/home/radxa/test.jpg

Here is the test code that I used:

import cv2
cap = cv2.VideoCapture(0) 

if not cap.isOpened():
    print("Don't open camera")
else:
    ret, frame = cap.read()
    if ret:
        cv2.imshow('frame', frame)
        cv2.waitKey(0)
    cap.release()
    cv2.destroyAllWindows()

Here is the error message that is being printed:

[ WARN:0] global /tmp/pip-req-build-6icxdfha/opencv/modules/videoio/src/cap_v4l.cpp (890) open VIDEOIO(V4L2:/dev/video0): can’t open camera by index

image

Does your opencv version have V4L2 and Gstreamer support compiled in? Run opencv_version -v to find out.

Some things you can try are to use the GStreamer backend as you know this is working, however if your OpenCV version is not have that compiled in then you will need to compile yourself.

1 Like

Thanks. I attempted to use GStreamer as the input for OpenCV.

import cv2
pipeline = "v4l2src ! video/x-raw, width=640, height=480, framerate=15/1 ! videoconvert ! videoscale ! video/x-raw, width=640, height=480 ! appsink"

cap = cv2.VideoCapture(pipeline, cv2.CAP_GSTREAMER)  

ret, frame = cap.read()
if ret:
    cv2.imshow('frame', frame)
    cv2.waitKey(0)
cap.release()
cv2.destroyAllWindows()

Subsequently, I discovered that my OpenCV does not support GStreamer. I will recompile my OpenCV at a later time.
image

By recompiling OpenCV, I have enabled GStreamer support, and consequently, successfully utilized GStreamer to access the Raspberry Pi Camera v2.

import cv2

pipeline = "v4l2src ! video/x-raw, width=640, height=480, framerate=15/1 ! videoconvert ! videoscale ! video/x-raw, width=640, height=480 ! appsink"
# cap = cv2.VideoCapture(pipeline, cv2.CAP_V4L) 
cap = cv2.VideoCapture(pipeline, cv2.CAP_GSTREAMER) 

while True:
    ret, frame = cap.read()
    if ret:
        cv2.imshow("frame", frame)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()