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"按钮,运行程序,则能够看到图像。

 

猜你喜欢

转载自www.cnblogs.com/ezrealiu/p/install-opencv-4-on-your-raspberry-pi-4.html