Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access webcam using OpenCV (Python) in Docker?

I'm trying to use Docker for one of our projects which uses OpenCV to process webcam feed (Python). But I can't seem to get access to the webcam within docker, here's the code which I use to test webcam access:

python -c "import cv2;print(cv2.VideoCapture(0).isOpened())"

And here's what I tried so far,

 docker run --device=/dev/video0 -it rec bash

 docker run --privileged --device=/dev/video0 -it rec bash

 sudo docker run --privileged --device=/dev/video0:/dev/video0 -it rec bash

All of these return False, what am I doing wrong?

like image 862
Grim Reaper Avatar asked Jun 30 '17 18:06

Grim Reaper


3 Answers

The Dockerfile in the link you provided doesn't specify how opencv was installed, can you provide the Dockerfile you used? Or how you installed opencv?

VideoCapture(0) won't work if you install opencv via pip.

You're using --device=/dev/video0:/dev/video0 correctly.

like image 70
pale bone Avatar answered Oct 02 '22 03:10

pale bone


Try to use this:

-v /dev/video0:/dev/video0

in place of

--device=/dev/video0 

and execute:

$ xhost + 

before docker run

like image 22
Jorge Ivan Rivalcoba Rivas Avatar answered Oct 02 '22 01:10

Jorge Ivan Rivalcoba Rivas


The easisest way I found to have a dockerized OpenCV able to connect to your webcam is by using the following Dockerfile :

FROM ubuntu:20.04

ENV TERM=xterm
ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get install -y --no-install-recommends \
    libopencv-dev \
    python3-opencv \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

WORKDIR /app
ADD . /app

ENV PYTHONUNBUFFERED=1
ENV PYTHONPATH=/app

and then build it and run in this way :

docker build -t opencv-webcam .
docker run -it -v $PWD:/app/ --device=/dev/video0:/dev/video0 -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY opencv-webcam bash

and run the following script inside the container with python3 script.py:

import cv2


WINDOW_NAME = "Opencv Webcam"

def run():

    cv2.namedWindow(WINDOW_NAME)

    video_capture = cv2.VideoCapture(0)

    while True:
        ret, frame = video_capture.read()
        print(ret, frame.shape)

        cv2.imshow(WINDOW_NAME, frame)
        cv2.waitKey(1)

if __name__ == "__main__":
    run()
like image 1
fallino Avatar answered Oct 02 '22 02:10

fallino