由于项目需要使用安卓平台下opencv的扩展库,对于通用的opencv库, opencv官网提供了android的SDK
但未能提供扩展库,因此需要自己进行源码编译。本文记录android平台下opencv及其扩展库的交叉编译。
前提:主机已安装android-ndk交叉编译器
安装依赖环境
sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg-dev libswscale-dev libtiff5-dev
sudo apt-get install libgtk2.0-dev
sudo apt-get install pkg-config
1、源码下载
下载opencv,可手动下载源码和拓展模块源码,解压后分别命名opencv和opencv_contrib文件
Releases - OpenCV
GitHub - opencv/opencv at 4.8.0
GitHub - opencv/opencv_contrib: Repository for OpenCV's extra modules
2、源码编译
设置编译脚本build-opencv-for-android.sh
#!/bin/bash
NDK_ROOT="${1:-${ANDROID_NDK_HOME}}"
SHELL_PATH=$(pwd)
echo $NDK_ROOT
### ABIs setup
declare -a ANDROID_ABI_LIST=("arm64-v8a")
### path setup
INSTALL_DIR="${SHELL_PATH}/android_opencv"
rm -rf "${INSTALL_DIR}/opencv"
### Make each ABI target iteratly and sequentially
API_LEVEL=21
for i in "${ANDROID_ABI_LIST[@]}"
do
ANDROID_ABI="${i}"
echo "Start building ${ANDROID_ABI} version"
TEMP_BUILD_DIR="${SHELL_PATH}/build/android_${ANDROID_ABI}"
# ### Remove the build folder first, and create it
rm -rf "${TEMP_BUILD_DIR}"
mkdir -p "${TEMP_BUILD_DIR}"
cd "${TEMP_BUILD_DIR}"
OPENCV_PATH="${SHELL_PATH}/opencv"
OPENCV_CONTRIB_PATH="${SHELL_PATH}/opencv_contrib"
INSTALL_PATH=${SHELL_PATH}/out/
mkdir -p "${INSTALL_PATH}"
/usr/cmake-3.23.0-rc2-linux-x86_64/bin/cmake -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON \
-DCMAKE_TOOLCHAIN_FILE="${NDK_ROOT}/build/cmake/android.toolchain.cmake" \
-DANDROID_TOOLCHAIN=clang++ \
-DANDROID_NDK="${NDK_ROOT}" \
-DANDROID_NATIVE_API_LEVEL=${API_LEVEL} \
-DANDROID_ABI="${ANDROID_ABI}" \
-DOPENCV_EXTRA_MODULES_PATH=${OPENCV_CONTRIB_PATH}/modules \
-DCMAKE_INSTALL_PREFIX=${INSTALL_PATH} \
-D BUILD_ANDROID_PROJECTS=OFF\
-D WITH_CUDA=OFF \
-D WITH_MATLAB=OFF \
-D BUILD_ANDROID_EXAMPLES=ON \
-D BUILD_DOCS=OFF \
-D BUILD_PERF_TESTS=OFF \
-D BUILD_TESTS=OFF \
${OPENCV_PATH}
# # Build it
make -j4
# # Install it
make install/strip
# ### Remove temp build folder
cd "${SHELL_PATH}"
# rm -rf "${TEMP_BUILD_DIR}"
echo "end building ${INSTALL_PATH} version"
done
将build-opencv-for-android.sh、opencv和opencv_contrib文件放置于同一目录下
导出NDK安装路径环境变量
export ANDROID_HOME=/usr/android-ndk-r25c/
export ANDROID_NDK_HOME=/usr/android-ndk-r25c/
./build-opencv-for-android.sh
等待编译完成,完成后,编译成功如下,库文件在 ./out/sdk/native/staticlibs/
本文在编译脚本中只设置了安卓arm64-v8a硬件平台的编译,如有需要可自行修改。
问题:编译完成后,不知道为什么,编译没有报错,但在3rdparty目录下并未编译 libtbb.a,可直接使用将官网sdk中的libtbb.a。
参考
GitHub - ShikinChen/build-opencv-for-android: 编译opencv的Android库的脚本
GitHub - tzutalin/build-opencv-for-android: An interactive script to download and build OpenCV and OpenCV contrib for Android