Install OpenCV 4 on your Raspberry Pi4


在樹莓派4上安裝OpenCV4

1. 前言


 

1.1. 參考資料

  1. Install OpenCV 4 on your Raspberry Pi:中文網站上關於樹莓派上安裝OpenCV4的文章大多來自於此,為眾多開發者的提供了極大的幫助。
  2. 編譯OpenCV以及openc_contrib提示缺少boostdesc_bgm.i文件出錯的解決:網絡的不佳可能會導致缺少部分文件。

1.2. 心理准備

  1. 整個安裝過程總時長約4個小時,絕大多數時間耗費在 cmake 的步驟上。
  2. 安裝途中,可能會遇到各種各樣的小問題,然而在互聯網上都能夠得到解決方法。
  3. 使用此方法能夠在RaspberryPi4順利安裝OpenCV4。

 “不麻痹、不厭戰、不松勁,咬緊牙關一鼓作氣!”

2. 准備


 

2.1. 樹莓派

  1. 終端,一般而言有如下方式開啟終端:
    1. SSH;
    2. VNC;
    3. HDMI + 顯示器。
  2. 聯網,應確保樹莓派能夠連接互聯網,一般而言有如下方式聯網:
    1. 網線;
    2. Wi-Fi。
  3. 攝像頭,安裝完畢后,豈不趕緊看看效果?
    1. CSI攝像頭。

2.2. 安裝包

當前(2020年6月15日)最新發布包是 4.3.0 版本,激進的開發者當仁不讓會選擇最新的開發版本。

訪問Github下載以下源碼包:

  1. opencv:opencv-4.3.0.tar.gz
  2. opencv_contrib:opencv_contrib-4.3.0.tar.gz

注意:直接下載的opencvopencv_contril壓縮包名稱都為"4.3.0.tar.gz,需注意區分。

3. 系統配置


 

3.1. 擴展文件系統

在安裝opencv之前需要確保安裝其依賴包,文件系統的空間可能不足,因此需要擴展文件系統以包含整個SD的空間。

  1. 鍵入 df -h 查看空間使用情況,92%已使用表明當前迫切需要擴展文件系統。
    $ df -h
    文件系統        容量  已用  可用 已用% 掛載點
    /dev/root     7.0G  6.1G  602M   92% /
    devtmpfs     1.8G     0  1.8G    0% /dev
    tmpfs          1.9G     0  1.9G    0% /dev/shm
    tmpfs          1.9G  8.5M  1.9G    1% /run
    tmpfs          5.0M  4.0K  5.0M    1% /run/lock
    tmpfs          1.9G     0  1.9G    0% /sys/fs/cgroup
    /dev/mmcblk0p1  253M   52M  201M   21% /boot
    tmpfs          386M     0  386M    0% /run/user/1000
  2. 鍵入 sudo rasp-con ,打開配置工具。
  3. 按動 ↑[\Up] 、 ↓[\Down] 、 Enter 鍵,依次選擇“ 7 Advanced Options Configure advanced settings ”-->“ A1 Expand Filesystem Ensures that all of the SD card storage is available to the ”-->“ Finish ”。
  4. 回到終端后,鍵入 sudo reboot 以重啟樹莓派。
  5. 重新通過 SSH 連接樹莓派后,鍵入 df -h 命令后,可以看到文件系統容量已擴展至整張SD卡,再無空間不夠之虞。
    $ df -h
    文件系統        容量  已用  可用 已用% 掛載點
    /dev/root        29G  6.1G  22.1G   23% /
    devtmpfs        1.8G     0  1.8G    0% /dev
    tmpfs           1.9G     0  1.9G    0% /dev/shm
    tmpfs           1.9G  8.5M  1.9G    1% /run
    tmpfs           5.0M  4.0K  5.0M    1% /run/lock
    tmpfs           1.9G     0  1.9G    0% /sys/fs/cgroup
    /dev/mmcblk0p1  253M   52M  202M   21% /boot
    tmpfs           386M     0  386M    0% /run/user/1000

3.2. 安裝依賴包

  1.  系統更新,鍵入 sudo apt-get update && sudo apt-get upgrade ,更新軟件包列表。
    $ sudo apt-get update && sudo apt-get upgrade
    命中:1 http://mirrors.tuna.tsinghua.edu.cn/raspbian/raspbian buster InRelease
    命中:2 http://mirrors.tuna.tsinghua.edu.cn/raspberrypi buster InRelease
    正在讀取軟件包列表... 完成
    正在讀取軟件包列表... 完成
    正在分析軟件包的依賴關系樹
    正在讀取狀態信息... 完成
    正在計算更新... 完成
    ...
  2. 安裝常用圖像工具包。
    sudo apt-get install libjpeg8-dev libtiff5-dev libjasper-dev libpng12-dev
  3. 安裝常用視頻工具包。
    sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
    sudo apt-get install libxvidcore-dev libx264-dev
  4. 安裝GTK。
    sudo apt-get install libgtk-3-dev
    sudo apt-get install libcanberra-gtk*
  5. 安裝OpenCV數值優化函數包。
    sudo apt-get install libatlas-base-dev gfortra
    
  6. 安裝Python 3。
    sudo apt-get install python3-dev
    
  7. 升級 pip 並安裝 numpy 。
    $ wget https://bootstrap.pypa.io/get-pip.py
    $ sudo python3 get-pip.py
    $ sudo pip3 install numpy
    Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
    Requirement already satisfied: numpy in /usr/lib/python3/dist-packages (1.16.2)

4. opencv安裝


 

4.1. 安裝包解壓

  1. 將“opencv-4.3.0.tar.gz與"opencv_contrib-4.3.0.tar.gz拷貝至 /home/pi 路徑下。
  2. 解壓“opencv-4.3.0.tar.gz”到當前路徑,並修改文件夾為 opencv (國際慣例)。
    tar zxvf opencv-4.3.0.tar.gz
    mv opencv-4.3.0 opencv
    
  3. 解壓“opencv_contrib-4.3.0.tar.gz”到當前路徑,並修改文件夾為 opencv_contrib (同上)。
    tar zxvf opencv_contrib-4.3.0.tar.gz
    mv opencv_contrib-4.3.0 opencv_contrib
    tar zxvf opencv_contrib-4.3.0.tar.gz
    mv opencv_contrib-4.3.0 opencv_contrib
    tar zxvf opencv_contrib-4.3.0.tar.gz
    mv opencv_contrib-4.3.0 opencv_contrib

4.2. cmake

  1. 進入opencv目錄。
    cd opencv
  2. 創建並進入build目錄。
    mkdir build
    cd build/
  3. 執行cmake。
    cmake -D CMAKE_BUILD_TYPE=RELEASE \
       -D CMAKE_INSTALL_PREFIX=/usr/local \
       -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \
       -D ENABLE_NEON=ON \
       -D ENABLE_VFPV3=ON \
       -D BUILD_TESTS=ON \
       -D OPENCV_ENABLE_NONFREE=ON \
       -D INSTALL_PYTHON_EXAMPLES=ON \
       -D INSTALL_C_EXAMPLES=ON \
       -D BUILD_EXAMPLES=ON ..

Note:

編譯選項:
CMAKE_BUILD_TYPE:編譯方式;
CMAKE_INSTALL_PREFIX:安裝目錄;
OPENCV_EXTRA_MODULES_PATH:額外模塊的路徑;
ENABLE_NEON:啟用neon;
ENABLE_VFPV3:啟用vfpvfp;
BUILD_TESTS:編譯測試例程;
OPENCV_ENABLE_NONFREE:啟用nonfree;
INSTALL_PYTHON_EXAMPLES:安裝官方Python例程;
INSTALL_C_EXAMPLES:安裝官方C例程;
BUILD_EXAMPLES:編譯例程。

合理配置`cmake`配置項,加快編譯速度。
已知在編譯**examples**時會產生編譯錯誤。

-- General configuration for OpenCV 4.3.0 =====================================
--   Version control:               unknown
--
--   Extra modules:
--     Location (extra):            /home/pi/opencv_contrib/modules
--     Version control (extra):     unknown
--
--   Platform:
--     Timestamp:                   2020-06-15T14:28:32Z
--     Host:                        Linux 4.19.75-v7l+ armv7l
--     CMake:                       3.13.4
--     CMake generator:             Unix Makefiles
--     CMake build tool:            /usr/bin/make
--     Configuration:               RELEASE
--
--   CPU/HW features:
--     Baseline:                    VFPV3 NEON
--       requested:                 DETECT
--       required:                  VFPV3 NEON
--
--   C/C++:
--     Built as dynamic libs?:      YES
--     C++ standard:                11
--     C++ Compiler:                /usr/bin/c++  (ver 8.3.0)
--     C++ flags (Release):         -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
--     C++ flags (Debug):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
--     C Compiler:                  /usr/bin/cc
--     C flags (Release):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
--     C flags (Debug):             -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
--     Linker flags (Release):      -Wl,--gc-sections -Wl,--as-needed
--     Linker flags (Debug):        -Wl,--gc-sections -Wl,--as-needed
--     ccache:                      NO
--     Precompiled headers:         NO
--     Extra dependencies:          dl m pthread rt
--     3rdparty dependencies:
--
--   OpenCV modules:
--     To be built:                 aruco bgsegm bioinspired calib3d ccalib core datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor ml objdetect optflow phase_unwrapping photo plot python2 python3 quality rapid reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab xfeatures2d ximgproc xobjdetect xphoto
--     Disabled:                    world
--     Disabled by dependency:      -
--     Unavailable:                 alphamat cnn_3dobj cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv hdf java js matlab ovis sfm viz xfeatures2d
--     Applications:                tests perf_tests examples apps
--     Documentation:               NO
--     Non-free algorithms:         YES
--
--   GUI:
--     GTK+:                        YES (ver 3.24.5)
--       GThread :                  YES (ver 2.58.3)
--       GtkGlExt:                  NO
--     VTK support:                 NO
--
--   Media I/O:
--     ZLib:                        /usr/lib/arm-linux-gnueabihf/libz.so (ver 1.2.11)
--     JPEG:                        /usr/lib/arm-linux-gnueabihf/libjpeg.so (ver 62)
--     WEBP:                        build (ver encoder: 0x020f)
--     PNG:                         /usr/lib/arm-linux-gnueabihf/libpng.so (ver 1.6.36)
--     TIFF:                        /usr/lib/arm-linux-gnueabihf/libtiff.so (ver 42 / 4.1.0)
--     JPEG 2000:                   build Jasper (ver 1.900.1)
--     OpenEXR:                     build (ver 2.3.0)
--     HDR:                         YES
--     SUNRASTER:                   YES
--     PXM:                         YES
--     PFM:                         YES
--
--   Video I/O:
--     DC1394:                      NO
--     FFMPEG:                      YES
--       avcodec:                   YES (58.35.100)
--       avformat:                  YES (58.20.100)
--       avutil:                    YES (56.22.100)
--       swscale:                   YES (5.3.100)
--       avresample:                NO
--     GStreamer:                   NO
--     v4l/v4l2:                    YES (linux/videodev2.h)
--
--   Parallel framework:            pthreads
--
--   Trace:                         YES (with Intel ITT)
--
--   Other third-party libraries:
--     Lapack:                      NO
--     Eigen:                       NO
--     Custom HAL:                  YES (carotene (ver 0.0.1))
--     Protobuf:                    build (3.5.1)
--
--   OpenCL:                        YES (no extra features)
--     Include path:                /home/pi/opencv/3rdparty/include/opencl/1.2
--     Link libraries:              Dynamic load
--
--   Python 2:
--     Interpreter:                 /usr/bin/python2.7 (ver 2.7.16)
--     Libraries:                   /usr/lib/arm-linux-gnueabihf/libpython2.7.so (ver 2.7.16)
--     numpy:                       /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.16.2)
--     install path:                lib/python2.7/dist-packages/cv2/python-2.7
--
--   Python 3:
--     Interpreter:                 /usr/bin/python3 (ver 3.7.3)
--     Libraries:                   /usr/lib/arm-linux-gnueabihf/libpython3.7m.so (ver 3.7.3)
--     numpy:                       /usr/lib/python3/dist-packages/numpy/core/include (ver 1.16.2)
--     install path:                lib/python3.7/dist-packages/cv2/python-3.7
--
--   Python (for build):            /usr/bin/python2.7
--
--   Java:
--     ant:                         /usr/bin/ant (ver 1.10.5)
--     JNI:                         NO
--     Java wrappers:               NO
--     Java tests:                  NO
--
--   Install to:                    /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /home/pi/opencv/build
cmake

4.3. 增大SWAP空間

  1. 看到其他開發者編譯opencv時由於SWAP過小,導致編譯失敗。在這兒,增大SWAP空間至2GB。
    $ sudo vi /etc/dphys-swapfile
    # ------------------>
    # set size to absolute value, leaving empty (default) then uses computed value
    #   you most likely don't want this, unless you have an special disk situation
    #CONF_SWAPSIZE=100
    CONF_SWAPSIZE=2048

     Note:  
    在編譯完成后,應當將`CONF_SWAPSIZE`改回100MB。

  2. 重新啟動交換服務。
    sudo /etc/init.d/dpshys-swapfile stop
    sudo /etc/init.d/dphys-swapfile start

4.4. 執行編譯(make)

4.4.1. make -j4

編譯。在此分配4個核心來進行編譯。

$ make -j4
Scanning dependencies of target libprotobuf
Scanning dependencies of target libwebp
Scanning dependencies of target libjasper
Scanning dependencies of target IlmImf
[  0%] Building C object 3rdparty/libjasper/CMakeFiles/libjasper.dir/jas_cm.c.o
[  0%] Building C object 3rdparty/libwebp/CMakeFiles/libwebp.dir/src/dec/alpha_dec.c.o
[  0%] Building CXX object 3rdparty/protobuf/CMakeFiles/libprotobuf.dir/src/google/protobuf/arena.cc.o
[  0%] Building C object 3rdparty/libwebp/CMakeFiles/libwebp.dir/src/dec/buffer_dec.c.o
[  0%] Building CXX object 3rdparty/openexr/CMakeFiles/IlmImf.dir/Half/half.cpp.o
[  0%] Building C object 3rdparty/libwebp/CMakeFiles/libwebp.dir/src/dec/frame_dec.c.o
[  0%] Building C object 3rdparty/libjasper/CMakeFiles/libjasper.dir/jas_debug.c.o
[  0%] Building C object 3rdparty/libwebp/CMakeFiles/libwebp.dir/src/dec/idec_dec.c.o

4.4.2. 編譯報錯

4.4.2.1. fatal error: boostdesc_bgm.i
/home/pi/opencv_contrib/modules/xfeatures2d/src/boostdesc.cpp:654:20: fatal error: boostdesc_bgm.i: 沒有那個文件或目錄
           #include ""
                    ^~~~~~~~~~~~~~~~~

解決方法:

[編譯OpenCV以及openc_contrib提示缺少boostdesc_bgm.i文件出錯的解決](https://blog.csdn.net/u011736771/article/details/85960300)

錯誤:

~/opencv_contrib/modules/xfeatures2d/src/boostdesc.cpp:673:20: > fatal error: boostdesc_bgm.i: No such file or directory
解決方式:

采用的是源碼編譯的方式,所以可以查看 build 文件夾下的日志文件 > CMakeDownloadLog.txt,在日志文件CMakeDownloadLog.txt中搜索boostdesc_bgm.i 關鍵詞 (不是在文件夾中搜索),
發現這個文件下載失敗了。日志文件里就有它的下載地址,直接復制其下載地址到網> 頁可以看該到文件的源碼,直接拷貝源碼並生存同名文件,放在 opencv_contrib/> modules/xfeatures2d/src/ 路徑下即可。

總共缺了以下幾個文件,都需要拷貝:

    boostdesc_bgm.i
    boostdesc_bgm_bi.i
    boostdesc_bgm_hd.i
    boostdesc_lbgm.i
    boostdesc_binboost_064.i
    boostdesc_binboost_128.i
    boostdesc_binboost_256.i
    vgg_generated_120.i
    vgg_generated_64.i
    vgg_generated_80.i
    vgg_generated_48.i

參考:
[fatal error: boostdesc_bgm.i: No such file or directory](https://github.com/opencv/opencv_contrib/issues/1301)

ps: 不懂操作的,點開上面這個網址往下拉,有人提供了缺失的各個文件的鏈接,點> 擊保存. 或者直接在這個網頁里搜索 BenbenIO 這個用戶的回復.

4.4.2.2. opencv error: ‘SURF’ has not been declared
  1. opencv_contrib沒有找到響應的頭文件,對比 ~/opencv/modules/features2d/test/ 與 ~/opencv_contrib/modules/xfeatures2d/test/ ,將 opencv_contrib 缺少的“.hpp”文件拷貝一份。
    • test_descriptors_invariance.impl.hpp
    • test_descriptors_regression.impl.hpp
    • test_detectors_invariance.impl.hpp
    • test_detectors_regression.impl.hpp
    • test_invariance_utils.hpp
    • 注意:沒有test_precomp.hpp文件。
  2. 將 ~/opencv/modules/features2d/test/ 中的“test_*.cpp”頭文件引用路徑修改為當前路徑。
    // Before Modify
    // #include "features2d/test/test_detectors_regression.impl.hpp"
    // #include "features2d/test/test_descriptors_regression.impl.hpp"
    
    // Now
    #include "test_detectors_regression.impl.hpp"
    #include "test_descriptors_regression.impl.hpp"

     參見:[樹莓派安裝OpenCV-4.1.0及Contrib](https://blog.csdn.net/qq_27971677/article/details/90400118)

4.5. install

sudo make install
sudo ldconfig

5. 測試用例


 

5.1. 查看opencv版本號

鍵入如下命令,看到版本號為 4.3.0 則表明安裝成功。

python

在 python 中輸入如下命令。

Python 2.7.16 (default, Oct 10 2019, 22:02:15)
[GCC 8.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'4.3.0'

5.2. 打開攝像頭

  1. 使用VNC連接樹莓派。
  2. 依次點擊 `編程`-->Thonny Python IDE
  3. 輸入如下的代碼。
    import cv2
    cap=cv2.VideoCapture(0)  #調用攝像頭‘0’一般是打開電腦自帶攝像頭,‘1’是打開外部攝像頭(只有一個攝像頭的情況)
    width=960
    height=600
    cap.set(cv2.CAP_PROP_FRAME_WIDTH,width)#設置圖像寬度
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT,height)#設置圖像高度
    #顯示圖像
    while True:
        ret,frame=cap.read()#讀取圖像(frame就是讀取的視頻幀,對frame處理就是對整個視頻的處理)
        #print(ret)#
        #######例如將圖像灰度化處理,
        img=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)#轉灰度圖
        cv2.imshow("img",img)
        ########圖像不處理的情況
        frame = cv2.flip( frame, 0 )
        frame = cv2.flip( frame, 1 )
        cv2.imshow("frame", frame)
    
        input=cv2.waitKey(20)
        if input==ord('q'):#如過輸入的是q就break,結束圖像顯示,鼠標點擊視頻畫面輸入字符
            break
    
    cap.release()#釋放攝像頭
    cv2.destroyAllWindows()#銷毀窗口
  4. 點擊"run"按鈕,運行程序,則能夠看到圖像。

 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM