一、删除系统自带的Opencv
使用jetpack安装的jetson,自带了opencv,但是没有cuda加速的,输入opencv_version
查看。
使用jtop
查看,可以确认自带的opencv是没用cuda的。
卸载opencv
pip3 uninstall opencv-python
sudo apt purge libopencv*
sudo apt autoremove
sudo apt update
二、安装OpenCV with CUDA的依赖
1)安装后面编译需要用到的依赖库
sudo apt install -y build-essential checkinstall cmake pkg-config yasm git gfortran
sudo apt install -y libjpeg8-dev libjasper-dev libtiff5-dev libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev libxine2-dev libv4l-dev
sudo apt install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libgtk2.0-dev libtbb-dev libatlas-base-dev libfaac-dev libmp3lame-dev libtheora-dev libvorbis-dev libxvidcore-dev libopencore-amrnb-dev libopencore-amrwb-dev x264 v4l-utils
sudo apt install python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libdc1394-22-dev
2)安装libpng12-0
sudo add-apt-repository ppa:linuxuprising/libpng12
sudo apt update
sudo apt install libpng12-0
若不慎安装了libpng12-dev
,会出现如下报错,原因是libpng12-dev
与libpng12-0
冲突,则需要卸载libpng12-dev
,再次安装libpng12-0
。
sudo apt-get remove libpng12-dev
3)若没有安装python,需要安装python
终端输入python
若报错,则安装sudo apt-get install python-dev
或者sudo apt-get install python3-dev
,需要安装python3.8版本,默认安装的就是3.8版本,ubuntu20.04已经去掉了python2版本。
三、下载编译安装OpenCV with CUDA
3.1 下载OpenCV源码
下载OpenCV4.5.5源码
https://github.com/opencv/opencv_contrib/archive/refs/tags/4.5.5.zip
https://github.com/opencv/opencv/archive/refs/tags/4.5.5.zip
其它版本见
https://github.com/opencv/opencv_contrib/tags
https://github.com/opencv/opencv/releases
3.2 编译OpenCV
1)新建文件夹~/opencv
,把opencv-4.5.5.zip
和opencv_contrib-4.5.5.zip
文件都解压在该文件夹下面。
mkdir ~/opencv
cd ~/opencv
mkdir build &cd build
cd opencv-4.5.5
mkdir build &cd build
2)编译命令修改
这里需要注意的点如下:
- 1.修改CUDA Arch BIN的版本,通过
jtop
查看CUDA Arch BIN的版本
- 2.这里
-DOPENCV_EXTRA_MODULES_PATH=/home/nvidia/opencv/opencv_contrib-4.5.5/modules \
需要改为opencv_contrib-4.5.5.zip
文件的路径
3)编译OpenCV
注意:如果有安装anaconda,建议关闭conda环境,进入主机环境后再编译,因为conda屏蔽了某些主机环境的库,导致编译时链接到了conda的库而冲突报错。
进入build
文件夹,CMake编译生成Makefile文件
cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr/local \
-DOPENCV_ENABLE_NONFREE=1 \
-DBUILD_opencv_python2=1 \
-DBUILD_opencv_python3=1 \
-DWITH_FFMPEG=1 \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda \
-DCUDA_ARCH_BIN=8.7 \
-DCUDA_ARCH_PTX=8.7 \
-DWITH_CUDA=1 \
-DENABLE_FAST_MATH=1 \
-DCUDA_FAST_MATH=1 \
-DWITH_CUBLAS=1 \
-DOPENCV_GENERATE_PKGCONFIG=1 \
-DOPENCV_EXTRA_MODULES_PATH=/home/nvidia/opencv/opencv_contrib-4.5.5/modules \
..
make编译和安装,编译大概需要40min。
make -j8
sudo make install
4)安装opencv的python包
cd ~/opencv/opencv-4.5.5/build/python_loader
sudo pip3 install .
参考:
https://zhuanlan.zhihu.com/p/678890471
https://blog.csdn.net/weixin_52303102/article/details/136846684
https://blog.csdn.net/qq_39422817/article/details/134611876
https://blog.csdn.net/weixin_45901764/article/details/113943439