Ubuntu 14.04 64位上默认安装了两个版本的python,一个是python2.7.6,另外一个是python3.4.3。这里使用OpenCV最新的稳定版本3.4.2在Ubuntu上安装python3.4.3支持OpenCV的操作步骤如下:
1. 更新包,执行:
sudo apt-get update
sudo apt-get upgrade
2. 安装依赖(若下面的依赖库本地已安装则略过),执行
sudo apt-get install build-essential cmake git pkg-config
sudo apt-get install libjpeg8-dev libtiff4-dev libjasper-dev libpng12-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libgtk2.0-dev
sudo apt-get install libatlas-base-dev gfortran
3. 从GitHub中下载最新opencv及opencv_contrib源码3.4.2: opencv-3.4.2.zip, opencv_contrib-3.4.2.zip
4. 将它们存放到/home/spring/Soft/opencv3.4.2目录下,解压缩,并改名,执行:
unzip opencv-3.4.2.zip; mv opencv-3.4.2 opencv
unzip opencv_contrib-3.4.2.zip; mv opencv_contrib-3.4.2 opencv_contrib
5. opencv的python库需要依赖Numpy,安装Numpy步骤可以参考:https://blog.csdn.net/fengbingchun/article/details/81590102
6. 编译不带cuda的opencv,因为本地/usr/local/lib目录下已存在opencv2.4.13的库,这里将其安装到/opt/opencv3.4.2目录下,进入到opencv目录下,依次执行:
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=/opt/opencv3.4.2 -DINSTALL_C_EXAMPLES=ON -DINSTALL_PYTHON_EXAMPLES=ON -DOPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules -DBUILD_EXAMPLES=ON ..
执行后结果如下:
执行:
make -j4
执行后结果如下:
注意:
(1). 为了加快编译速度,可以将编译examples选项关闭,即
-DINSTALL_C_EXAMPLES=OFF -DINSTALL_PYTHON_EXAMPLES=OFF -DBUILD_EXAMPLES=OFF
(2). 在编译stitching模块时会提示找不到cuda.hpp即matchers.hpp:52:42: fatal error: opencv2/xfeatures2d/cuda.hpp: No such file or directory,解决方法是在opencv/modules/stitching/CMakeLists.txt文件中加入一条语句使其include opencv_contrib/modules/xfeatures2d/include,可以是绝对路径,如
INCLUDE_DIRECTORIES("/home/spring/Soft/opencv3.4.2/opencv_contrib/modules/xfeatures2d/include")
(3). 在编译opencv_contrib/modules/xfeatures2d时会提示找不到boostdesc_bgm.i,即boostdesc.cpp:653:37: fatal error: boostdesc_bgm.i: No such file or directory,解决方法是手动下载所需的*.i文件,下载地址 http://answers.opencv.org/question/113942/cmake-failing-with-hash-mismatch/%E4%B8%AD%E6%9C%89%E7%9B%B8%E5%BA%94%E7%9A%84 ,然后将这些*.i文件拷贝到opencv_contrib/modules/xfeatures2d/src目录下;或者更新CMake到最新3.12.1,在重装CMake之前,先安装curl,执行
sudo apt-get install libcurl4-gnutls-dev
CMake源码的安装步骤可以参考:https://blog.csdn.net/fengbingchun/article/details/51159348
安装CMake时添加--system-curl选项,即
./bootstrap --system-curl
强烈推荐后面的方法,因为除了下载*.i文件,还需要用同样的方法下载其它所需文件。
执行:
sudo make install
执行完后将会在/opt/opencv3.4.2目录下产生4个目录:bin, include, lib, share,在lib/python3.4/dist-packages目录下会生成cv2.cpython-34m.so
7. 验证
将cv2.cpython-34m.so软链接到/usr/lib/python3/dist-packages目录下,执行:
sudo ln -s /opt/opencv3.4.2/lib/python3.4/dist-packages/cv2.cpython-34m.so /usr/lib/python3/dist-packages
test_opencv_1.py内容如下:
import cv2
print(cv2.__version__)
执行结果如下: