SpiritShaman's Blog

python3.5+opencv3.x+ubuntu17.04 环境搭建

第一步 更新

$ sudo apt-get update
$ sudo apt-get upgrade

第二步 环境搭建

1 必要软件

$ sudo apt-get install build-essential cmake cmake-qt-gui pkg-config git

2 图像格式相关

$ sudo apt-get install libpng-dev libjpeg-dev libtiff5-dev

3 GUI相关

$ sudo apt-get install libgtk2.0-dev

4 视频格式相关

$ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
$ sudo apt-get install libxvidcore-dev libx264-dev

5 C++多线程相关

$ sudo apt-get install libtbb2 libtbb-dev

6 摄像头相关

$ sudo apt-get install libdc1394-22-dev

7 opengl相关

$ sudo apt-get install libgtkglext1 libgtkglext1-dev

8 矩阵运算相关

$ sudo apt-get install libatlas-base-dev gfortran

9 python

$ sudo apt-get install python3.5-dev python2.7-dev

第三步 下载opencv源代码

$ cd ~
$ mkdir opencv
$ wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.1.0.zip
$ unzip opencv.zip
$ wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.1.0.zip
$ unzip opencv_contrib.zip

第四步 配置python环境

1 下载安装pip

配置python环境第一步就是安装pip

$ cd ~
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py

2 安装python虚拟环境

$ sudo pip install virtualenv virtualenvwrapper
$ sudo rm -rf ~/get-pip.py ~/.cache/pip

3 修改~/.bashrc文件

(此处是为python虚拟环境添加变量)

$ vim ~/.bashrc

在末尾处添加

# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

保存退出

$ source ~/.bashrc

4 创建python虚拟环境

(本教程为python3方法,python2步骤类似)

$ mkvirtualenv cv -p python3
(此处 python2 即为 mkvirtualenv cv -p python2 ,以后步骤类似)
$ workon cv

如下图检测自己是否在虚拟环境中,如若不在,再执行workon cv

5 为虚拟环境安装numpy

$ pip install numpy

第五步 配置和编译安装opencv

请确保你在Python虚拟环境中

$ cd /home/ssssix40/opencv/opencv-3.1.0
$ mkdir build
$ cd build
$ cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D INSTALL_C_EXAMPLES=OFF \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv/opencv_contrib-3.1.0/modules \
    -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \
    -D ENABLE_PRECOMPILED_HEADERS=OFF \
    -D BUILD_EXAMPLES=ON ..

完成之后应该会出现下面的内容

然后就是

$ make
//这里需要很长时间
$ sudo make install
$ sudo ldconfig

第六步 完成安装

查看是否存在包

$ ls -l /usr/local/lib/python3.5/site-packages/
total 1972
-rw-r--r-- 1 root staff 2016816 Sep 13 17:24 cv2.cpython-35m-x86_64-linux-gnu.so

建立软链接

$ cd /usr/local/lib/python3.5/site-packages/
$ sudo mv cv2.cpython-35m-x86_64-linux-gnu.so cv2.so
$ cd ~/.virtualenvs/cv/lib/python3.5/site-packages/
$ ln -s /usr/local/lib/python3.5/site-packages/cv2.so cv2.so

测试opencv

$ cd ~
$ workon cv
$ python
Python 3.5.2 (default, Jul  5 2016, 12:43:10) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'3.1.0'
>>>

问题解决

1. OpenCV 3.1下载 ippicv_linux_20151201失败

http://blog.csdn.net/huangkangying/article/details/53406370

待续

#Python-Opencv #环境搭建