最近在安装Active SLAM,要求opencv with contrib and non-free enabled. 因为docker 安装的ubuntu18.04自带python2 和 python3, 所以在安装opencv的时候最好指明python版本,否则即使安装成功, import cv2也会找不到模块。
中间还是折腾了一下,因此这里写一下安装过程。
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install build-essential cmake unzip pkg-config
sudo apt-get install libjpeg-dev libpng-dev libtiff-dev
sudo apt-get install libjasper-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libxvidcore-dev libx264-dev
sudo apt-get install libgtk-3-dev
sudo apt-get install libatlas-base-dev gfortran
sudo apt-get install python3.6-dev
这里说明一下:libjasper-dev安装的时候,可能会报错:libjasper-dev being missing 之类的
我参考网上各种方式,我都安装不上,有看到说不需要的,我就不管了。
如果想试一下的,可以参考:https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv/ (这也是本文重点参考的网站之一)
sudo add-apt-repository "deb http://security.ubuntu.com/ubuntu xenial-security main"
sudo apt update
sudo apt install libjasper1 libjasper-dev
安装pip:
wget https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py
pip3 install numpy
注意opencv和opencv_contrib的版本号一定要对应!
cd ~
wget -O opencv.zip https://github.com/opencv/opencv/archive/3.4.3.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/3.4.3.zip
unzip opencv.zip
unzip opencv_contrib.zip
如果解压后的文件夹带版本后缀,可以重命名:
mv opencv-3.4.3 opencv
mv opencv_contrib-3.4.3 opencv_contrib
将opencv_contrib文件夹移入opencv下:
mv ./opencv_contrib/ ./opencv/
build + install:
cd opencv
mkdir build && cd build
cd build
重点来了: cmake的时候注意修改OPENCV_EXTRA_MODULES,PYTHON3_LIBRARIES,PYTHON3_NUMPY_INCLUDE_DIRS ,与自己本机地址对应, 可以用 whereis python3
查找相关地址。
cmake -D BUILD_opencv_python3=YES -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES=~/opencv/opencv_contrib/modules -D PYTHON3_LIBRARIES=/usr/lib/aarch64-linux-gnu/libpython3.6m.so -D PYTHON3_NUMPY_INCLUDE_DIRS=/usr/local/lib/python3.6/dist-packages/numpy/core/include/ \ -D BUILD_EXAMPLES=ON \ -D WITH_CUDA=OFF \ -D OPENCV_ENABLE_NONFREE=ON \ -D INSTALL_PYTHON_EXAMPLES=ON ..
make
sudo make install
查看是否安装成功:
pkg-config --modversion opencv
输出3.4.3
即安装成功。
此处参考:https://blog.csdn.net/samsu0108/article/details/121963233
sudo gedit /etc/ld.so.conf.d/opencv.conf
在文件末尾添加(空白文件也是正常的)
/usr/local/lib
保存后,执行
sudo ldconfig
配置bash:
sudo gedit /etc/bash.bashrc
在文件末尾添加
PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
export PKG_CONFIG_PATH
保存后,执行:
source /etc/bash.bashrc
使用python3引用import cv2, 如果没有报错,即安装和配置成功。
pip3 install opencv-python
pip3 install opencv-contrib-python