OpenCV 编译安装

于 2022.5.16 在 Ubuntu 22.04 x86_64 测试

注:本文流程针对 C++ 和 Python3 两种语言支持

安装依赖

sudo apt update
sudo apt install -y libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libxvidcore-dev libx264-dev libatlas-base-dev gfortran libgtk2.0-dev libjpeg-dev libpng-dev libgtk-3-dev libdc1394-dev libtesseract-dev libtiff-dev libatlas-base-dev libdw-dev libunwind-dev libgmp-dev libgsl-dev libgslcblas0 flex bison libgst-dev libcap-dev build-essential cmake git pkg-config ffmpeg libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libvulkan-dev libvulkan1 mesa-vulkan-drivers vulkan-tools
# Python 编译安装:https://blog.iyatt.com/?p=1784
# 我是安装的 Python 3.10.4

# 更换国内镜像站 - 北京外国语大学
pip3 install -i https://mirrors.bfsu.edu.cn/pypi/web/simple --upgrade pip
pip3 config set global.index-url https://mirrors.bfsu.edu.cn/pypi/web/simple

pip3 install numpy==1.22.3

获取源码

源码分为两部分,基础的核心库为 opencv,专利算法、研发中的功能、高级扩展功能在 contrib。注意在配置编译前先准备好科学上网,否则无法下载依赖,会导致编译失败。

git clone https://github.com/opencv/opencv.git --branch 4.5.5 --depth=1

cd opencv

git clone https://github.com/opencv/opencv_contrib.git --branch 4.5.5 --depth=1

配置编译

  • 编译静态库,加上参数 -DBUILD_SHARED_LIBS=OFF
  • CUDA 加速,请先按此文配置相关环境:https://blog.iyatt.com/?p=2224,配置加上参数:-DWITH_CUDA=ON
mkdir build && cd build

cmake -DCMAKE_BUILD_TYPE=RELEASE \
-DBUILD_opencv_python2=OFF \
-DBUILD_opencv_python3=ON \
-DOPENCV_ENABLE_NONFREE=ON \
-DBUILD_TESTS=OFF \
-DBUILD_FAT_JAVA_LIB=OFF \
-DBUILD_EXAMPLES=OFF \
-DCMAKE_INSTALL_PREFIX=/usr/local \
-DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules \
-DOPENCV_GENERATE_PKGCONFIG=ON \
-DWITH_VULKAN=ON ..

编译安装

sudo make install -j$(nproc)

配置环境变量

sudo -s
echo "/usr/local/lib" >> /etc/ld.so.conf.d/opencv.conf
ldconfig
echo "export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig" >> /etc/bash.bashrc
source /etc/bash.bashrc
exit

验证安装

DNN 计算加速

net 为 DNN 模块加载的模型对象

1.CUDA

net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

2.Vulkan

net.setPreferableBackend(cv2.dnn.DNN_BACKEND_VKCOM)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_VULKAN)

3.OpenCL

net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL)

发表回复