1.下载openCV
1) https://github.com/opencv/opencv/archive/${version}.zip
2) https://github.com/opencv/opencv_contrib/archive/${version}.zip
按照如上连接下载自己需要的opencv版本,注意将${version}替换为自己需要的版本号,笔者这里下载的是{version="4.8.0"}。
2.安装openCV的依赖库
sudo apt-get update
sudo apt-get install -y build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
sudo apt-get install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
sudo apt-get install -y python3.10-dev python-dev python-numpy python3-numpy
sudo apt-get install -y libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libdc1394-dev
sudo apt-get install -y libv4l-dev v4l-utils qv4l2 v4l2ucp #摄像头模块,报错可忽略
sudo apt-get install -y curl
请根据实际情况修改python版本并且保证除摄像头模块无报错后再进行下一步。
3.编译openCV
1)将两个zip解压到要安装的文件夹。
unzip opencv-${version}.zip
unzip opencv_contrib-${version}.zip
rm opencv-${version}.zip opencv_contrib-${version}.zip
cd opencv-${version}/
2)创建release文件夹
mkdir release
cd release/
3)cmake
sudo cmake -D WITH_CUDA=ON -D WITH_CUDNN=ON -D CUDA_ARCH_BIN="7.5" -D CUDA_ARCH_PTX="" -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.8.0/modules -D WITH_GSTREAMER=ON -D WITH_LIBV4L=ON -D BUILD_opencv_python3=ON -D PYTHON_DEFAULT_EXECUTABLE=/usr/bin/python3.10 -D PYTHON3_EXECUTABLE=/usr/bin/python3.10 -D PYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.10.so -D PYTHON3_INCLUDE_DIR=/usr/include/python3.10 -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D BUILD_EXAMPLES=ON -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..
注意,CUDA_ARCH_BIN要根据显卡算力来选,rtx2060是7.5,jetson agx orin是8.6
4)make -j$(nproc)
nproc # 查看核数
sudo make -jx #x是核数,加速编译
5)install opencv
sudo make install
4.配置环境变量
sudo gedit ~/.bashrc
添加
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
export PYTHONPATH=/usr/local/lib/python3.10/dist-packages/:$PYTHONPATH
更新
source ~/.bashrc
5.验证是否安装成功
import cv2
print(cv2.getBuildInformation())