之前也安装过OpenCV,但是一直没有总结成完整的一套步骤,之前遇到很多问题最后都是玄学方法解决的。这次要写一次完整的过程。

主要参考资料是http://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/

安装步骤整理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
sudo apt update
sudo apt upgrade

# some developer tools:
sudo apt install build-essential cmake pkg-config

# image I/O libraries that actually facilitate the loading and decoding process.
sudo apt install libjpeg8-dev libtiff5-dev libjasper-dev libpng12-dev

# process video streams and access frames from cameras:
sudo apt install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt install libxvidcore-dev libx264-dev

# The highgui module relies on the GTK library
sudo apt install libgtk-3-dev

# optimize various functionalities inside OpenCV, such as matrix operations:
sudo apt install libatlas-base-dev gfortran

# installing the Python development headers and libraries for both Python 2.7 and Python 3.5 (that way you have both):
sudo apt install python2.7-dev python3.5-dev
1
2
3
4
5
6
7
8
cd ~/Downloads

wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.2.0.zip
unzip opencv.zip

# the full install of OpenCV 3 to have access to features (no pun intended) such as SIFT and SURF.
wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.1.0.zip
unzip opencv_contrib.zip
1
2
3
4
5
6
7
8
9
10
cd opencv-3.2.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_contrib-3.2.0/modules \
-D PYTHON_EXECUTABLE=usr/bin/python3 \
-D BUILD_EXAMPLES=ON ..
1
2
3
make -j4
sudo make install
sudo ldconfig

然后如果想在python虚拟环境中使用cv2.so,可以用软链接的方式。

1
2
cd ~/.virtualenvs/cv/lib/python3.5/site-packages/
ln -s /usr/local/lib/python3.5/site-packages/cv2.so cv2.so

还有就是写c++的话,可以用cmake来配置项目:

1
2
3
4
5
cmake_minimum_required(VERSION 2.8)
project( test )
find_package( OpenCV REQUIRED )
add_executable( main main.cpp )
target_link_libraries( main ${OpenCV_LIBS} )