由于需要在i.MX6ULL上使用OpenCV库,前几天成功在Windows系统中完成了对OpenCV启用了NEON的交叉编译,在此记录一下过程。总的来说不算麻烦。

环境准备

  将make.exe放在MSYS2安装位置的usr/bin目录下,并将通过在MSYS2控制台中输入make -v确保正常运行。
  注意GCC编译器版本。我之前使用的是较低的4.9.4版本,在编译过程中会发生错误。

CMake配置

编辑CMakeLists.txt

  打开OpenCV目录下的CMakeLists.txt,添加set(ENABLE_NEON_ON)set(CMAKE_SYSTEM_PROCESSOR arm),效果如下:

...
# Disable in-source builds to prevent source tree corruption.
if(" ${CMAKE_SOURCE_DIR}" STREQUAL " ${CMAKE_BINARY_DIR}")
  message(FATAL_ERROR "
FATAL: In-source builds are not allowed.
       You should create a separate directory for build files.
")
endif()

set(ENABLE_NEON_ON)
set(CMAKE_SYSTEM_PROCESSOR  arm)

include(cmake/OpenCVMinDepVersions.cmake)

if(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore)
  cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
  #Required to resolve linker error issues due to incompatibility with CMake v3.0+ policies.
  #CMake fails to find _fseeko() which leads to subsequent linker error.
  #See details here: http://www.cmake.org/Wiki/CMake/Policies
  cmake_policy(VERSION 2.8)
else()
  cmake_minimum_required(VERSION "${MIN_VER_CMAKE}" FATAL_ERROR)
endif()
...

cmake-gui操作

  选择源码目录和构建目录:
图片-1678205839695

  单击左下角“Configure”按钮,按下图选择:
图片-1678195804853

  填写相关信息:
图片-1678195960138

  单击Finish按钮,等待完成后,按下图配置NEON:
图片-1678196226448

  单击Generate按钮,生成构建文件,等待完成。

开始编译

  打开MSYS2,cd到build目录下,输入make -j4(“j”后面的数为编译线程数,可根据电脑配置调整),等待运行完成,即编译成功。
图片-1678197971843

其他

收集include和library

  对引用了OpenCV的项目进行编译时,我们需要用到OpenCV的头文件和库文件。在Linux中我们可以在make命令完成后完成后输入make install命令就会自动安装在系统目录下,但我们目前在Windows系统中,上述命令安装完成后只能在MSYS2环境中使用。于是我写了一段bat脚本用于收集include和library文件(注意修改代码中的路径):

@echo off
setlocal enabledelayedexpansion

if not exist .\opencv2 md .\opencv2
if not exist .\lib md .\lib

xcopy "C:\Developement\opencv-4.7.0\build\opencv2\cvconfig.h" ".\opencv2" > nul
xcopy "C:\Developement\opencv-4.7.0\build\opencv2\opencv_modules.hpp" ".\opencv2" > nul
xcopy "C:\Developement\opencv-4.7.0\include\opencv2\opencv.hpp" ".\opencv2" > nul

for /d /r "C:\Developement\qt\opencv-4.7.0\modules\" %%i in (*) do (
    set pathname=%%i
    if /i "!pathname:~-15!" == "include\opencv2" (
        xcopy "!pathname!" ".\opencv2" /E /I /Y > nul
    )
)

for /r "C:\Developement\opencv-4.7.0\build\lib" %%i in (*.so) do (
    xcopy "%%i" ".\lib" /E /I /Y > nul
)

  将上代码保存为以.bat结尾的文件并运行,就会自动收集相关文件到当前位置的lib和opencv2目录下。

参考

windows下Linaro-arm-linux编译开启NEON的Opencv源码详细过程
OpenCV交叉编译中遇到的错误及解决方案

Q.E.D.