环境准备
OpenCV 4.5.5
Android NDK r23b
- 网址:https://developer.android.google.cn/ndk/downloads
- 解压并配置环境变量
export ANDROID_NDK=/home/opencv/android/android-ndk
(替换成自己的解压目录)
libfacedetection 源码
网址:https://github.com/ShiqiYu/libfacedetection.git
编译
构建
libfacedetection 源码目录下执行下述操作
mkdir build
cd build
cmake .. -DCMAKE_INSTALL_PREFIX=install \
-DCMAKE_BUILD_TYPE=MinSizeRel \
-DCMAKE_TOOLCHAIN_FILE=${ANDROID_NDK}/build/cmake/android.toolchain.cmake \
-DANDROID_ABI="arm64-v8a" \
-DANDROID_PLATFORM=android-18 \
-DUSE_OPENMP=OFF \
-DENABLE_NEON=ON \
-DENABLE_AVX2=OFF \
-DDEMO=OFF
cmake --build . --config MinSizeRel
编译参数:https://developer.android.google.cn/ndk/guides/cmake
共享库:-DBUILD_SHARED_LIBS=ON
参数 | 可选项 | 意义 |
---|---|---|
ANDROID_ABI | armeabi-v7a armeabi-v7a with NEON arm64-v8a x86 x86_64 | 目标 ABI |
ANDROID_ARM_MODE | arm thumb | 指定是为 armeabi-v7a 生成 arm 还是 thumb 指令 |
ANDROID_ARM_NEON | TRUE FALSE | 为 armeabi-v7a 启用或停用 NEON。对其他 ABI 没有影响。 对于 API 级别(minSdkVersion 或 ANDROID_PLATFORM)23 或更高版本, 默认为 true,否则为 false |
ANDROID_LD | lld default | 选择要使用的链接器。lld 目前处于 NDK 实验阶段,可通过此参数启用。 |
ANDROID_NATIVE_API_LEVEL | ANDROID_PLATFORM 的别名 | |
ANDROID_PLATFORM | android-$API_LEVEL $API_LEVEL android-$API_LETTER | 指定应用或库所支持的最低 API 级别。此值对应于应用的 minSdkVersion。 |
ANDROID_STL | c++_shared c++_static none system | 指定要为此应用使用的 STL |
安装
cmake --build . --config MinSizeRel --target install/strip
快捷方式
直接执行 ./build_android.sh
,于老师真是贴心。
编译 x86 和 x86_64 的,关闭 NEON
Android 平台使用
通过使能 -DBUILD_SHARED_LIBS=ON
,我们可以编译出主要架构下的共享库,然后配合 OpenCV Android SDK,即可在 Android 平台上快速使用,相比较之前介绍的方式,这种方式更完整,更符合维护习惯。
工程结构
CMakeLists.txt
cmake_minimum_required(VERSION 3.18.1)
project("detection")
message(${PROJECT_SOURCE_DIR})
SET(OpenCV_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include)
SET(OpenCV_SHARED_LIBS ${PROJECT_SOURCE_DIR}/../../../libs/${ANDROID_ABI})
SET(FaceDetection_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include)
SET(FaceDetection_SHARED_LIBS ${PROJECT_SOURCE_DIR}/../../../libs/${ANDROID_ABI})
find_library(android-lib android)
add_library( # Sets the name of the library.
detection
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
facedetectcnn-jni.cpp)
include_directories(${OpenCV_INCLUDE_DIRS})
include_directories(${FaceDetection_INCLUDE_DIRS})
add_library(libopencv_java4 SHARED IMPORTED )
set_target_properties(libopencv_java4 PROPERTIES
IMPORTED_LOCATION "${OpenCV_SHARED_LIBS}/libopencv_java4.so")
add_library(libfacedetection SHARED IMPORTED )
set_target_properties(libfacedetection PROPERTIES
IMPORTED_LOCATION "${FaceDetection_SHARED_LIBS}/libfacedetection.so")
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
target_link_libraries( # Specifies the target library.
detection
libopencv_java4
libfacedetection
${log-lib} )