樹莓派編譯安裝opencv3 (2019.1.6更新)

1、更新系統python

sudo apt-get update  
sudo apt-get upgrade  
sudo rpi-update
#重啓系統  
sudo reboot

2、安裝依賴庫及程序linux

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

3、編譯安裝FFMPEG
之因此要用編譯安裝是爲了確保opencv在cmake時ffmpeg選項爲on,這將關係到opencv可否播放視頻文件。
先卸載系統默認安裝的ffmpeggit

sudo apt-get remove ffmpeg

再下載源碼並安裝最新版ffmpeggithub

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目錄。bootstrap

4、安裝更新PYTHON及運行環境python2.7

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

5、下載、編譯安裝opencv
在opencv官網下載最新版源碼(目前3.X最新版爲3.4.5,注意contrib要和opencv的版本要保持一致),要確保opencv和opencv_contrib版本一致,不然會致使編譯失敗。curl

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

預編譯ide

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

6、部署到PYTHON系統庫(此步彷佛能夠跳過)
python2.7ui

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

7、配置環境
爲了使opencv可以正常打開SPI攝像頭須要編輯/etc/rc.local
在exit 0以前加入 modprobe bcm2835-v4l2

8、測試
編輯 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
相關文章
相關標籤/搜索