【问题标题】:Install OpenCV in a Docker container在 Docker 容器中安装 OpenCV
【发布时间】:2022-02-11 10:26:41
【问题描述】:

我正在尝试 Dockerise 一个依赖于 OpenCV 的 Python 应用程序。我尝试了几种不同的方法,但是当我尝试运行应用程序时,我不断得到...ImportError: No module named cv2

这是我当前的 Dockerfile。

FROM python:2.7

MAINTAINER Ewan Valentine <ewan@theladbible.com>

RUN mkdir -p /usr/src/app 
WORKDIR /usr/src/app 

# Various Python and C/build deps
RUN apt-get update && apt-get install -y \ 
    wget \
    build-essential \ 
    cmake \ 
    git \
    pkg-config \
    python-dev \ 
    python-opencv \ 
    libopencv-dev \ 
    libav-tools  \ 
    libjpeg-dev \ 
    libpng-dev \ 
    libtiff-dev \ 
    libjasper-dev \ 
    libgtk2.0-dev \ 
    python-numpy \ 
    python-pycurl \ 
    libatlas-base-dev \
    gfortran \
    webp \ 
    python-opencv 

# Install Open CV - Warning, this takes absolutely forever
RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ 
    cd opencv && \
    git checkout 3.0.0 && \
    cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \
    cd opencv_contrib && \
    git checkout 3.0.0 && \
    cd ~/opencv && mkdir -p build && cd build && \
    cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \ 
    -D INSTALL_C_EXAMPLES=ON \ 
    -D INSTALL_PYTHON_EXAMPLES=ON \ 
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ 
    -D BUILD_EXAMPLES=OFF .. && \
    make -j4 && \
    make install && \ 
    ldconfig

COPY requirements.txt /usr/src/app/
RUN pip install --no-cache-dir -r requirements.txt

COPY . /usr/src/app 

还有我的 requirements.txt 文件

Flask==0.8
gunicorn==0.14.2
requests==0.11.1
bs4==0.0.1
nltk==3.2.1
pymysql==0.7.2
xlsxwriter==0.8.5
numpy==1.11
Pillow==3.2.0
cv2==1.0
pytesseract==0.1

【问题讨论】:

    标签: python opencv docker


    【解决方案1】:

    使用稍微不同的设置进行了修复

    FROM python:2.7
    
    MAINTAINER Ewan Valentine <ewan@theladbible.com>
    
    RUN mkdir -p /usr/src/app 
    WORKDIR /usr/src/app 
    
    # Various Python and C/build deps
    RUN apt-get update && apt-get install -y \ 
        wget \
        build-essential \ 
        cmake \ 
        git \
        unzip \ 
        pkg-config \
        python-dev \ 
        python-opencv \ 
        libopencv-dev \ 
        libav-tools  \ 
        libjpeg-dev \ 
        libpng-dev \ 
        libtiff-dev \ 
        libjasper-dev \ 
        libgtk2.0-dev \ 
        python-numpy \ 
        python-pycurl \ 
        libatlas-base-dev \
        gfortran \
        webp \ 
        python-opencv \ 
        qt5-default \
        libvtk6-dev \ 
        zlib1g-dev 
    
    # Install Open CV - Warning, this takes absolutely forever
    RUN mkdir -p ~/opencv cd ~/opencv && \
        wget https://github.com/opencv/opencv/archive/3.0.0.zip && \
        unzip 3.0.0.zip && \
        rm 3.0.0.zip && \
        mv opencv-3.0.0 OpenCV && \
        cd OpenCV && \
        mkdir build && \ 
        cd build && \
        cmake \
        -DWITH_QT=ON \ 
        -DWITH_OPENGL=ON \ 
        -DFORCE_VTK=ON \
        -DWITH_TBB=ON \
        -DWITH_GDAL=ON \
        -DWITH_XINE=ON \
        -DBUILD_EXAMPLES=ON .. && \
        make -j4 && \
        make install && \ 
        ldconfig
    
    COPY requirements.txt /usr/src/app/
    RUN pip install --no-cache-dir -r requirements.txt
    
    COPY . /usr/src/app 
    

    【讨论】:

    • 不错的答案,是否可以用同样的方式安装c版的opencv?
    【解决方案2】:

    感谢您发布此信息。我遇到了同样的问题并尝试了您的解决方案,虽然它似乎安装了 OpenCV,但它给我留下了 Python 六库版本冲突的问题,所以我采取了不同的路线。我认为更简单的方法是在您的容器中安装 Anaconda,然后添加 OpenCV。我使用的是 Python 2,所以我安装 OpenCvv 的整个 Dockerfile 只是:

    FROM continuumio/anaconda
    EXPOSE 5000
    
    ADD . /code-directory
    WORKDIR code-directory
    RUN conda install opencv
    
    CMD ["python", "run-code.py"]
    

    这将从 continuumio/anaconda Dockerfile 安装 Anaconda,然后它将使用 Anaconda 安装 opencv。如果你也需要的话,还有一个用于 Python 3 的单独的 continuumio Dockerfile。

    【讨论】:

    • 嗨,无法将 conda 与 Docker 一起使用,它说 conda not found.
    【解决方案3】:

    这是一个image,它是在 Ubuntu 16.04 上使用 Python2 + Python3 + OpenCV 构建的。您可以使用 docker pull chennavarri/ubuntu_opencv_python

    这是 Dockerfile(在上面提到的同一个 dockerhub 存储库中提供),它将在 Ubuntu 16.04 上为 python2 和 python3 安装 opencv,并设置适当的 raw1394 链接。复制自https://github.com/chennavarri/docker-ubuntu-python-opencv

    FROM ubuntu:16.04
    MAINTAINER Chenna Varri
    
    RUN apt-get update
    RUN apt-get install -y build-essential apt-utils
    
    RUN apt-get install -y cmake git libgtk2.0-dev pkg-config libavcodec-dev \
      libavformat-dev libswscale-dev
    RUN  apt-get update && apt-get install -y python-dev python-numpy \
      python3 python3-pip python3-dev libtbb2 libtbb-dev \
      libjpeg-dev libjasper-dev libdc1394-22-dev \
      python-opencv libopencv-dev libav-tools python-pycurl \
      libatlas-base-dev gfortran webp qt5-default libvtk6-dev zlib1g-dev
    
    RUN pip3 install numpy
    
    RUN apt-get install -y python-pip
    RUN pip install --upgrade pip
    
    RUN cd ~/ &&\
        git clone https://github.com/Itseez/opencv.git &&\
        git clone https://github.com/Itseez/opencv_contrib.git &&\
        cd opencv && mkdir build && cd build && cmake  -DWITH_QT=ON -DWITH_OPENGL=ON -DFORCE_VTK=ON -DWITH_TBB=ON -DWITH_GDAL=ON -DWITH_XINE=ON -DBUILD_EXAMPLES=ON .. && \
        make -j4 && make install && ldconfig
    
    # Set the appropriate link
    RUN ln /dev/null /dev/raw1394
    
    RUN cd ~/opencv
    

    给刚开始接触 Docker 的人的一些额外说明:

    • 在你放置这个 Dockerfile 的目录中,构建 docker 镜像为docker build -t ubuntu_cv .

    • 镜像构建完成后,您可以通过docker images进行检查

      REPOSITORY   TAG       IMAGE ID      CREATED             SIZE
      
      ubuntu_cv  latest    6210ddd6346b   24 minutes ago      2.192 GB
      
    • 你可以用docker run -t -i ubuntu_cv:latest启动一个docker容器

    【讨论】:

      【解决方案4】:

      在 docker 中安装 Opencv (latest) ...步骤与 Linux 版本类似,只是符号链接路径不同:

      apt install -y libtiff5-dev libjpeg8-dev libpng-dev cmake make
      apt install -y libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev
      apt install -y libxine2-dev libv4l-dev
      apt install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
      apt install -y qt5-default
      apt install -y libatlas-base-dev
      apt install -y libfaac-dev libmp3lame-dev libtheora-dev
      apt install -y libvorbis-dev libxvidcore-dev
      apt install -y libopencore-amrnb-dev libopencore-amrwb-dev
      apt install -y x264 x265 v4l-utils
      apt install -y libprotobuf-dev protobuf-compiler
      apt install -y libeigen3-dev
      
      wget --output-document cv.zip https://github.com/opencv/opencv/archive/4.0.1.zip
      wget --output-document contrib.zip 
      https://github.com/opencv/opencv_contrib/archive/4.0.1.zip
      unzip cv.zip
      unzip contrib.zip
      cd opencv-4.0.1
      mkdir build
      cd build
      cmake -D CMAKE_BUILD_TYPE=RELEASE \
        -D CMAKE_INSTALL_PREFIX=/usr/local \
        -D WITH_TBB=ON \
        -D WITH_V4L=ON \
        -D WITH_QT=ON \
        -D WITH_OPENGL=ON \
        -D WITH_CUDA=ON \
        -D WITH_NVCUVID=OFF \
        -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.0.1/modules \
        -D OPENCV_ENABLE_NONFREE=ON \
        ..
      
      make -j 'number of gpu'
      make install 
      ldconfig
      ln -s /usr/local/lib/python3.6/dist-packages/cv2/python-3.6/cv2.cpython-36m-x86_64-linux-gnu.so /usr/local/lib/python3.6/dist-packages/cv2/python-3.6/cv2.so
      

      这对我有用!!

      【讨论】:

        【解决方案5】:
        from    ubuntu:12.10
        
        # Ubuntu sides with libav, I side with ffmpeg.
        run echo "deb http://ppa.launchpad.net/jon-severinsson/ffmpeg/ubuntu quantal main" >> /etc/apt/sources.list
        run apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1DB8ADC1CFCA9579
        
        
        run apt-get update
        run apt-get install -y -q wget curl
        run apt-get install -y -q build-essential
        run apt-get install -y -q cmake
        run apt-get install -y -q python2.7 python2.7-dev
        run wget 'https://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg' && /bin/sh setuptools-0.6c11-py2.7.egg && rm -f setuptools-0.6c11-py2.7.egg
        run curl 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py' | python2.7
        run pip install numpy
        run apt-get install -y -q libavformat-dev libavcodec-dev libavfilter-dev libswscale-dev
        run apt-get install -y -q libjpeg-dev libpng-dev libtiff-dev libjasper-dev zlib1g-dev libopenexr-dev libxine-dev libeigen3-dev libtbb-dev
        add build_opencv.sh /build_opencv.sh
        run /bin/sh /build_opencv.sh
        run rm -rf /build_opencv.sh
        

        【讨论】:

        • 应该在你的答案中包含 build_opencv.sh
        【解决方案6】:

        对于某些应用程序(如我的情况),您可以使用 python 包 opencv-python-headless。如果您所做的只是基于 CPU 的 opencv 活动,这将直接在 docker 映像中工作。

        
        WORKDIR /usr/src/app
        
        COPY requirements.txt ./
        RUN pip install --no-cache-dir -r requirements.txt
        
        COPY . .
        
        CMD [ "python", "./camera_controller.py" ]
        

        在 requirements.txt 中有这一行

        opencv-python-headless==<your version>
        

        【讨论】:

          【解决方案7】:

          我使用这个 Dockerfile,它就像一个魅力

          FROM python:3.9
          
          LABEL mantainer="Baher Elnaggar <eng.baher77@gmail.com>"
          
          WORKDIR /opt/build
          
          ENV OPENCV_VERSION="4.5.1"
          
          RUN apt-get -qq update \
              && apt-get -qq install -y --no-install-recommends \
                  build-essential \
                  cmake \
                  git \
                  wget \
                  unzip \
                  yasm \
                  pkg-config \
                  libswscale-dev \
                  libtbb2 \
                  libtbb-dev \
                  libjpeg-dev \
                  libpng-dev \
                  libtiff-dev \
                  libopenjp2-7-dev \
                  libavformat-dev \
                  libpq-dev \
              && pip install numpy \
              && wget -q https://github.com/opencv/opencv/archive/${OPENCV_VERSION}.zip -O opencv.zip \
          
          
          
          
          
          
              && unzip -qq opencv.zip -d /opt \
              && rm -rf opencv.zip \
              && cmake \
                  -D BUILD_TIFF=ON \
                  -D BUILD_opencv_java=OFF \
                  -D WITH_CUDA=OFF \
                  -D WITH_OPENGL=ON \
                  -D WITH_OPENCL=ON \
                  -D WITH_IPP=ON \
                  -D WITH_TBB=ON \
                  -D WITH_EIGEN=ON \
                  -D WITH_V4L=ON \
                  -D BUILD_TESTS=OFF \
                  -D BUILD_PERF_TESTS=OFF \
                  -D CMAKE_BUILD_TYPE=RELEASE \
                  -D CMAKE_INSTALL_PREFIX=$(python3.9 -c "import sys; print(sys.prefix)") \
                  -D PYTHON_EXECUTABLE=$(which python3.9) \
                  -D PYTHON_INCLUDE_DIR=$(python3.9 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
                  -D PYTHON_PACKAGES_PATH=$(python3.9 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
                  /opt/opencv-${OPENCV_VERSION} \
              && make -j$(nproc) \
              && make install \
              && rm -rf /opt/build/* \
              && rm -rf /opt/opencv-${OPENCV_VERSION} \
              && rm -rf /var/lib/apt/lists/* \
              && apt-get -qq autoremove \
              && apt-get -qq clean
          

          【讨论】:

          【解决方案8】:

          如果您想将 Opencv dnn 与 CUDA 一起使用,并将 torch 与 gpu(可选)一起使用,我推荐:

          FROM nvidia/cuda:10.2-base-ubuntu18.04
          
          WORKDIR /home
          
          ENV DEBIAN_FRONTEND=noninteractive
          ENV TZ=Europe/Minsk
          RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
          
          RUN apt-get update && apt-get install -y \
              keyboard-configuration \
              nvidia-driver-440\
              curl \
              ca-certificates \
              sudo \
              git \
              bzip2 \
              libx11-6 \
              cmake \
              g++ \
              wget \
              build-essential \ 
              cmake \ 
              git \
              unzip \ 
              pkg-config \
              python-dev \ 
              python-opencv \ 
              libopencv-dev \ 
              libjpeg-dev \ 
              libpng-dev \ 
              libtiff-dev \  
              libgtk2.0-dev \ 
              python-numpy \ 
              python-pycurl \ 
              libatlas-base-dev \
              gfortran \
              webp \ 
              python-opencv \ 
              qt5-default \
              libvtk6-dev \ 
              zlib1g-dev \
              libcudnn7=7.6.5.32-1+cuda10.2 \
              libcudnn7-dev=7.6.5.32-1+cuda10.2 \
              python3-pip \
              python3-venv \
              nano
          
          RUN alias python='/usr/bin/python3'
          RUN pip3 install numpy
          RUN pip3 install torch
          
          #RUN echo ############ && python --version && ##############
          
          # Install Open CV - Warning, this takes absolutely forever
          RUN git clone https://github.com/opencv/opencv_contrib  && \
              cd opencv_contrib  && \
              git fetch --all --tags  && \
              git checkout tags/4.3.0  && \
              cd .. && \
              git clone https://github.com/opencv/opencv.git  && \
              cd opencv  && \
              git checkout tags/4.3.0   
          
          #RUN pip3 freeze && which python3 && python3 --version
          
          ################################################################
          #################### OPENCV CPU ################################
          
          #RUN pwd &&\
          #    cd opencv  && \
          #    pwd &&\
          #    mkdir build && cd build && \
          #    pwd &&\
          #    cmake -DCMAKE_BUILD_TYPE=Release  \
          #      -DENABLE_CXX14=ON                 \
          #      -DBUILD_PERF_TESTS=OFF            \
          #      -DOPENCV_GENERATE_PKGCONFIG=ON    \
          #      -DWITH_XINE=ON                    \
          #      -DBUILD_TESTS=OFF                 \
          #      -DENABLE_PRECOMPILED_HEADERS=OFF  \
          #      -DCMAKE_SKIP_RPATH=ON             \
          #      -DBUILD_WITH_DEBUG_INFO=OFF       \
          #      -DOPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules  \
          #      
          #      -Dopencv_dnn_superres=ON /usr/bin/ .. && \
          #    make -j$(nproc) && \
          #    make install 
          
          ################################################################
          #################### OPENCV GPU ################################
          
          RUN cd opencv && mkdir build && cd build && \
              cmake -DCMAKE_BUILD_TYPE=Release \
              -D CMAKE_CXX_COMPILER=/usr/bin/g++ \
              -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) \
              -D BUILD_NEW_PYTHON_SUPPORT=ON \
              -D BUILD_opencv_python3=ON \
              -D HAVE_opencv_python3=ON \
              -D INSTALL_PYTHON_EXAMPLES=ON \
              -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-10.2 \
              -D CUDA_BIN_PATH=/usr/local/cuda-10.2 \
              -D CUDNN_INCLUDE_DIR=/usr/include/cudnn.h \
              -D WITH_CUDNN=ON \
              -D CUDA_ARCH_BIN=6.1 \
              -D OPENCV_DNN_CUDA=ON \
              -D WITH_CUDA=ON \
              -D BUILD_opencv_cudacodec=OFF \
              -D WITH_GTK=ON \
              -D CMAKE_BUILD_TYPE=RELEASE \
              -D CUDA_HOST_COMPILER:FILEPATH=/usr/bin/gcc-7 \
              -D ENABLE_PRECOMPILED_HEADERS=OFF \
              -D WITH_TBB=ON \
              -D WITH_OPENMP=ON \
              -D WITH_IPP=ON \
              -D BUILD_EXAMPLES=OFF \
              -D BUILD_DOCS=OFF \
              -D BUILD_PERF_TESTS=OFF \
              -D BUILD_TESTS=OFF \
              -D WITH_CSTRIPES=ON \
              -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
              -D CMAKE_INSTALL_PREFIX=/usr/local/ \
              -DBUILD_opencv_python3=ON         \
              -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) \
              -D PYTHON3_EXECUTABLE=$(which python3)  \
              -D PYTHON_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
              -D PYTHON3_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
              -D PYTHON3_LIBRARY=$(python3 -c "from distutils.sysconfig import get_config_var;from os.path import dirname,join ; print(join(dirname(get_config_var('LIBPC')),get_config_var('LDLIBRARY')))")  \
              -D PYTHON3_NUMPY_INCLUDE_DIRS=$(python3 -c "import numpy; print(numpy.get_include())")  \
              -D PYTHON3_PACKAGES_PATH=$(python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")  \
              -D OPENCV_GENERATE_PKGCONFIG=ON .. \
              -Dopencv_dnn_superres=ON /usr/bin/ .. && \ 
              make -j$(nproc) && \
              make install 
          
          RUN pip3 install opencv/build/python_loader
          

          然后你可以运行

          import torch
          import os
          
          print('availabe:',torch.cuda.is_available() )
          print('devices available', torch.cuda.device_count())
          print('device id:',torch.cuda.current_device() )
          print('device address', torch.cuda.device(0))
          print('gpu model',torch.cuda.get_device_name(0))
          
          device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
          print('Using device:', device)
          
          #Additional Info when using cuda
          if device.type == 'cuda':
              print(torch.cuda.get_device_name(0))
              print('Memory Usage:')
              print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
              print('Cached:   ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')
          
          import cv2
          print("DNN_BACKEND_CUDA",cv2.dnn.DNN_BACKEND_CUDA)
          print("DNN_BACKEND_CUDA",cv2.dnn.DNN_TARGET_CUDA)
          

          你会得到类似的东西:

          Using device: cuda
          availabe: True
          devices available 1
          device id: 0
          device address <torch.cuda.device object at 0x7f5a0a392550>
          gpu model GeForce GTX 1050 Ti
          Memory Usage:
          Allocated: 0.0 GB
          Cached:    0.0 GB
          DNN_BACKEND_CUDA 5
          DNN_BACKEND_CUDA 6
          

          【讨论】:

            猜你喜欢
            • 2017-11-11
            • 2017-05-02
            • 2014-07-06
            • 2020-12-20
            • 2021-05-11
            • 2021-07-09
            • 1970-01-01
            • 1970-01-01
            • 2022-10-05
            相关资源
            最近更新 更多