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

Viewed 4610
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
3 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.

First, I recommend checking the device path using ls -ltrh /dev/video* as stated here. The path of the device I wanted to use was /dev/video0. Then I added a flag with an appropriate device path --device /dev/video0 just after docker run. In particular, if you are creating a jupyter-notebooks directory you can write:

docker run --device /dev/video0 --gpus all -it -p 8888:8888 -v [directory-path]:/tf [image-name]

What worked for me was:

xhost local:docker
sudo docker run -it --rm --privileged --env="DISPLAY" --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" --device="/dev/video0:/dev/video0" ubuntu:latest

To check that the camera is working (change video0 with your device):

ffplay /dev/video0
Related