樹莓派安裝 OpenCV

步驟很多,記錄一下_

□ 安裝相關涵式庫

sudo apt-get update && sudo apt-get upgrade
sudo apt-get install build-essential cmake pkg-config
sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libxvidcore-dev libx264-dev
sudo apt-get install libgtk2.0-dev libgtk-3-dev
sudo apt-get install libcanberra-gtk*
sudo apt-get install libatlas-base-dev gfortran
sudo apt-get install python2.7-dev python3-dev

□ 下載OpenCV原始碼 (目前版本)

cd ~
wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.3.1.zip
unzip opencv.zip
wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.3.1.zip
unzip opencv_contrib.zip

□ 建立Python虛擬環境

wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
sudo python3 get-pip.py
sudo pip install virtualenv virtualenvwrapper
sudo rm -rf ~/.cache/pip
#修改設定檔
nano ~/.profile

#底下加入
# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

#重新載入設定檔
source ~/.profile
#建立虛擬環境 (python3+CV3.3.1)
mkvirtualenv py3cv331 -p python3

#也可以(python2+CV3.3.1)
mkvirtualenv py2cv331 -p python2
#進入虛擬環境
source ~/.profile
workon py2cv331

#安裝NumPy套件
pip install numpy

□ 編譯及安裝OpenCV

cd ~/opencv-3.3.1/
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.3.1/modules \
    -D ENABLE_NEON=ON \
    -D ENABLE_VFPV3=ON \
    -D BUILD_TESTS=OFF \
    -D INSTALL_PYTHON_EXAMPLES=OFF \
    -D BUILD_EXAMPLES=OFF ..

make
sudo make install
sudo ldconfig

□ 連結設定

#連結設定 (for Python 3)
cd /usr/local/lib/python3.5/site-packages/
sudo mv cv2.cpython-35m-arm-linux-gnueabihf.so cv2.so
cd ~/.virtualenvs/py3cv331/lib/python3.5/site-packages/
ln -s /usr/local/lib/python3.5/site-packages/cv2.so cv2.so

#連結設定 (for Python 2)
cd ~/.virtualenvs/py2cv331/lib/python2.7/site-packages/
ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so
#測試是否安裝成功
$ source ~/.profile
$ workon py2cv331
$ python
>>> import cv2
>>> cv2.__version__
'3.3.1'
>>>

□ 備註

sudo apt-get install libcanberra-gtk*
#或是
nano .bashrc
#加入
export NO_AT_BRIDGE=1

#可以修正以下錯誤
* (Original:10126): WARNING **: Error retrieving accessibility bus address:
 org.freedesktop.DBus.Error.ServiceUnknown: The name 
 org.a11y.Bus was not provided by any .service files

參考

https://www.pyimagesearch.com/2017/09/04/raspbian-stretch-install-opencv-3-python-on-your-raspberry-pi