树莓派编译安装opencv3 (2019.1.6更新)
一、更新系统
sudo apt-get update
sudo apt-get upgrade
sudo rpi-update
#重启系统
sudo reboot
二、安装依赖库及程序
sudo apt-get -y install build-essential git cmake pkg-config
sudo apt-get -y install libjpeg8-dev
sudo apt-get -y install libtiff5-dev
sudo apt-get -y install libjasper-dev
sudo apt-get -y install libpng12-dev
sudo apt-get -y install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get -y install libgtk2.0-dev
sudo apt-get -y install libsdl2-dev
sudo apt-get -y install libatlas-base-dev gfortran
sudo apt-get -y install libxvidcore-dev libx264-dev
三、编译安装FFMPEG
之所以要用编译安装是为了确保opencv在cmake时ffmpeg选项为on,这将关系到opencv能否播放视频文件。
先卸载系统默认安装的ffmpeg
sudo apt-get remove ffmpeg
再下载源码并安装最新版ffmpeg
git clone git://source.ffmpeg.org/ffmpeg.git
cd ffmpeg
./configure --enable-shared --disable-static
make -j4
sudo make install
export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig":$PKG_CONFIG_PATH
需要注意一下添加到环境变量PKG_CONFIG_PATH中的地址为ffmpeg编译后存放.pc文件的本地pkgconfig目录。
四、安装更新PYTHON及运行环境
sudo apt-get -y install python2.7-dev python3-dev
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install numpy
五、下载、编译安装opencv
在opencv官网下载最新版源码(目前3.X最新版为3.4.5,注意contrib要和opencv的版本要保持一致),要确保opencv和opencv_contrib版本一致,否则会导致编译失败。
wget -O opencv.zip https://github.com/opencv/opencv/archive/3.4.5.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/3.4.5.zip
unzip opencv.zip
unzip opencv_contrib.zip
预编译
cd ~/opencv
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.4.5/modules \
-D WITH_FFMPEG=ON \
-D BUILD_EXAMPLES=ON ..
编译opencv,在树莓派3中建议加上-j4参数,这样编译速度能快一点。
make -j4
sudo make install
sudo ldconfig
六、部署到PYTHON系统库(此步似乎可以跳过)
python2.7
ln -s /usr/local/lib/python2.7/dist-packages/cv2/python-2.7/cv2.so /usr/local/lib/python2.7/dist-packages/cv2.so
python 3.0
ln -s /usr/local/lib/python3.5/dist-packages/cv2/python-3.5/cv2.cpython-35m-arm-linux-gnueabihf.so /usr/local/lib/python3.5/dist-packages/cv2.so
七、配置环境
为了使opencv能够正常打开SPI摄像头需要编辑/etc/rc.local
在exit 0之前加入 modprobe bcm2835-v4l2
八、测试
编辑 cameratest.py,添加如下内容,保存并退出。
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
cap.set(3,640) # set Width
cap.set(4,480) # set Height
while(True):
ret, frame = cap.read()
frame = cv2.flip(frame, -1) # Flip camera vertically
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
cv2.imshow('gray', gray)
k = cv2.waitKey(30) & 0xff
if k == 27: # press 'ESC' to quit
break
cap.release()
cv2.destroyAllWindows()
执行
python cameratest.py
(lykyl原创,转载请注明出处)