Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to open camera using cv2.VideoCapture(0) in Docker Ubuntu host

import cv2

cam=cv2.VideoCapture(0)

while True:
    _,frame=cam.read()
    if frame is not None:
        cv2.imshow("frame",frame)

cam.release()

This is my code running for camera capture. I have runned an ubuntu image in which i have installed opencv using apt install python3-opencv.

It gives an error:

global ../modules/videoio/src/cap_v4l.cpp (887) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
like image 489
Pradyumn Joshi Avatar asked Sep 17 '25 05:09

Pradyumn Joshi


1 Answers

check if you using --device flag correctly. This is how I would run it :

docker run -it --rm --env="DISPLAY" --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" --device="/dev/video0:/dev/video0" test:0.1 python ./test_camera.py

You also need to provide --env="DISPLAY" --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" for docker to connect to the screen. Before running docker, use this command xhost local:docker to give access for the docker user group to use the screen.

like image 175
Darius Grigaliunas Avatar answered Sep 19 '25 20:09

Darius Grigaliunas