概述

安装opencv有很多种方式,我列出了三种方式。并针对第二种方式进行了详细的安装解释,强烈推荐使用第三种方式。

1.从Ubuntu源安装opencv

1
sudo apt-get install libopencv-dev python-opencv

2.从opencv官方源代码安装

1.安装opencv所依赖的包

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# KEEP UBUNTU OR DEBIAN UP TO DATE
sudo apt-get -y update
sudo apt-get -y upgrade
sudo apt-get -y dist-upgrade
sudo apt-get -y autoremove
# install package
sudo apt-get install build-essential cmake pkg-config
sudo apt-get install libatlas-base-dev gfortran
# GUI (if you want to use GTK instead of Qt, replace 'qt5-default' with 'libgtkglext1-dev' and remove '-DWITH_QT=ON' option in CMake):
sudo apt-get install -y qt5-default libvtk6-dev

# Media I/O:
sudo apt-get install -y zlib1g-dev libjpeg-dev libwebp-dev libpng-dev libtiff5-dev libjasper-dev libopenexr-dev libgdal-dev

# Video I/O:
sudo apt-get install -y libdc1394-22-dev libavcodec-dev libavformat-dev libswscale-dev libtheora-dev libvorbis-dev libxvidcore-dev libx264-dev yasm libopencore-amrnb-dev libopencore-amrwb-dev libv4l-dev libxine2-dev

# Parallelism and linear algebra libraries:
sudo apt-get install -y libtbb-dev libeigen3-dev

# Python:
sudo apt-get install -y python-dev python-tk python-numpy python3-dev python3-tk python3-numpy

# Java:
sudo apt-get install -y ant default-jdk

# Documentation:
sudo apt-get install -y doxygen

2.下载opencv和opencv_contrib源代码

1
2
3
4
wget -O opencv.zip https://github.com/opencv/opencv/archive/3.2.0.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/3.2.0.zip
unzip opencv.zip
unzip opencv_contrib.zip

3.为opencv创建独立虚拟话环境

1
2
3
mkvirtualenv -p python3.5 cvdl
workon cvdl
pip install numpy

4.配置和安装opencv

1
2
3
4
5
6
7
8
9
cd opencv-3.2.0
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=/usr/local -DWITH_QT=ON -DWITH_OPENGL=ON -DFORCE_VTK=ON -DWITH_TBB=ON -DWITH_GDAL=ON -DWITH_XINE=ON -DPYTHON_EXECUTABLE=~/.virtualenvs/cvdl/bin/python -DINSTALL_PYTHON_EXAMPLES=ON -DOPENCV_EXTRA_MODULES_PATH=~/project/cvdl/opencv_contrib/modules -DBUILD_EXAMPLES=ON ..
# PYTHON_EXECUTABLE: python执行环境,当然也可以指定为python2.7
# OPENCV_EXTRA_MODULES_PATH:opencv第三方的模块。
make -j4
sudo make install
sudo ldconfig

5.安装成功的opencv作用到全局

1
2
3
4
5
6
ls -l /usr/local/lib/python3.5/site-packages/
#在安装完之后会有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/cvdl/lib/python3.5/site-packages
ln -s /usr/local/lib/python3.5/site-packages/cv2.so cv2.so

6.测试安装是否成功 打开ipython,输入如下:

1
2
3
4
ipython
import cv2
cv2.__version__
#如果提示正常代表安装成功

7.删除源包

1
rm -rf opencv opencv_contrib opencv.zip opencv_contrib.zip

3.从Anaconda安装oepncv环境

我们需要建立一个虚拟化的独立环境

1
2
3
conda create -n cv3 python=3.6
source activate cv3
conda install -c https://conda.anaconda.org/menpo opencv3