Cannot open camera 0 with cv2.VideoCapture(0) on Linux Python OpenCV

大家好,我目前遇到以下問題:我想用 cv2.VideoCapture(0) 打開相機 0,但如果相機打不開,程式就會印出「無法打開相機0」然後直接 exit。下面是我執行的狀況截圖:

messageImage_1713766991368.jpg

我的環境是 Linux,儲存路徑是 /home/cy/photos/,用 Python + OpenCV (cv2)。

程式碼是這樣:

import cv2
from datetime import datetime
import time

cap0 = cv2.VideoCapture(0)
if not cap0.isOpened():
    print("無法打開相機0")
    exit()
    
ret0, frame0 = cap0.read()
time.sleep(1)

if ret0 :

    filename = datetime.now().strftime("%Y%m%d_%H%M%S")

    cv2.imwrite('/home/cy/photos/photo0_{}.jpg'.format(filename), frame0)
cap0.release()

執行後就直接印「無法打開相機0」了,想請問是不是我的用法有問題?

Thanks for sharing the script and the screenshot. Since that message comes from your own cap0.isOpened() check, it means OpenCV was not able to open the device at index 0.

Before we dig into the code, a couple of quick checks:

  1. Can you confirm the camera model — is this the Arducam B0196 UVC camera?
  2. Does the system see the camera at all? Please run lsusb and v4l2-ctl --list-devices and paste the output here if you can.

Thanks for the reply. Yes, the camera is the B0196. I did check lsusb / v4l2-ctl and the device does show up, but I didn’t save the text logs — the only thing I have is the execution screenshot I posted earlier. Even though the system sees the camera, cv2.VideoCapture(0) still gives isOpened() == False.

Got it, thanks for confirming. Looking at your script, the overall flow is fine — VideoCapture(0) → isOpened() → read() → time.sleep(1) → imwrite() — but the very first step is failing. isOpened() returns False, so the script never even reaches read() or imwrite(), and that’s why you see 無法打開相機0 before it exits.

The likely issue is how OpenCV is being told to open the device. On Linux, plain cv2.VideoCapture(0) with the default backend often won’t initialize Arducam UVC cameras correctly, even when the device shows up fine in lsusb / v4l2-ctl. For Arducam UVC cameras on Linux, the recommended approach is to use OpenCV Python with a GStreamer pipeline instead of relying only on cv2.VideoCapture(0).

We have sample code that covers exactly this setup — please refer to it here:
https://docs.arducam.com/UVC-Camera/Appilcation-Note/OpenCV-Python-GStreamer-on-linux/

The idea is to build a GStreamer pipeline string and pass it to cv2.VideoCapture(...), which gives OpenCV the correct source and format parameters for these UVC cameras. Try adapting your capture code to that sample and see if isOpened() returns True. Let us know how it goes.