一、更新系統
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