1 安装CMAKE
sudo apt-get install cmake
2 安装python及其所依赖的软件包
sudo apt-get install build-essential
sudo apt-get install git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
sudo apt-get install python3-dev python3-numpy libtbb2 libtbb-dev libjpeg-dev libpng12-dev libtiff5-dev libjasper-dev libdc1394-22-dev
3 从opencv官网下载opencv源码
wget -c https://github.com/opencv/opencv/archive/3.2.0.zip
unzip .2.0.zip
4 编译
在解压后的文件夹中新建build文件夹,用来存放编译文件
mkdir build
cd build
# 在电脑上有多个版本的python时,可以通过-D PYTHON_DEFAULT_EXECUTABLE=$(which python3)来确定使用哪个版本的python
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) -D WITH_TBB=ON -D WITH_EIGEN=ON ..
#没有问题后
make
sudo make install
5 安装Contrib模块
OpenCV3之后有些模块在称为opencv_contrib的资源库中,比如人脸识别模块等。
#下载opencv_contrib
#在build同级目录下
mkdir opencv_contrib
cd opencv_contrib
wget -c https://github.com/opencv/opencv_contrib/archive/3.2.0.zip
#解压
unzip 3.2.0.zip
#重新运行cmake
cd ../build
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) -D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/3.2.0/modules/ -D WITH_TBB=ON -D WITH_EIGEN=ON ..
#make & make install
make
sudo make install
6 验证是否安装成功
在终端运行python3
import CV2 #如果没有出错,就说明安装成功了
- 1
7 打开摄像头例子
import cv2
capture = cv2.VideoCapture(0)
while True:
ret, img = capture.read()
if img is not None:
cv.imshow('camera', img)
if cv.waitKey(10) & 0xFF == ord(' '):
break
capture.release()
cv.destroyAllWindows()
参考:
[1] https://docs.opencv.org/3.1.0/d7/d9f/tutorial_linux_install.html
[2] https://stackoverflow.com/questions/37070304/how-to-build-opencv-for-python3-when-both-python2-and-python3-are-installed
[3] https://github.com/opencv/opencv
[4] https://github.com/opencv/opencv_contrib