下载opencv
https://github.com/opencv/opencv/releases
编译指令
cmake .. -G "Ninja" \
-DCMAKE_TOOLCHAIN_FILE="G:/SDK/ndk/26.0.10792818/build/cmake/android.toolchain.cmake" \
-DANDROID_NDK="G:/SDK/ndk/26.0.10792818" \
-DANDROID_ABI="arm64-v8a" \
-DANDROID_NATIVE_API_LEVEL=21 \
-DCMAKE_BUILD_TYPE=Release \
-DANDROID_STL=c++_shared \
-DBUILD_SHARED_LIBS=ON \
-DANDROID_TOOLCHAIN=clang \
-DANDROID_PLATFORM=android-21 \
-DCMAKE_VERBOSE_MAKEFILE=ON \
-DBUILD_ANDROID_PROJECTS=OFF \
-DBUILD_ANDROID_EXAMPLES=OFF \
-DBUILD_JAVA=OFF
cmake .. -G "Ninja" -DCMAKE_TOOLCHAIN_FILE="G:/SDK/ndk/26.0.10792818/build/cmake/android.toolchain.cmake" \
-DANDROID_NDK="G:/SDK/ndk/26.0.10792818" \
-DANDROID_ABI="armeabi-v7a" \
-DANDROID_NATIVE_API_LEVEL=21 \
-DCMAKE_BUILD_TYPE=Release \
-DANDROID_STL=c++_shared \
-DBUILD_SHARED_LIBS=ON \
-DANDROID_TOOLCHAIN=clang \
-DANDROID_PLATFORM=android-21 \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_VERBOSE_MAKEFILE=ON \
-DBUILD_ANDROID_PROJECTS=OFF \
-DBUILD_ANDROID_EXAMPLES=OFF \
-DBUILD_JAVA=OFF
ninja
报错 Android SDK Build Tools: directory doesn’t exist:
-- Performing Test HAVE_CXX_WNO_COMMA - Success
-- Update variable ANDROID_HOME from environment: G:/SDK/platform-tools
-- Android SDK: using location: G:/SDK/platform-tools
CMake Error at cmake/android/OpenCVDetectAndroidSDK.cmake:101 (message):
Android SDK Build Tools: directory doesn't exist:
G:/SDK/platform-tools/build-tools Use BUILD_ANDROID_PROJECTS=OFF to prepare
Android project files without building them
Call Stack (most recent call first):
cmake/android/OpenCVDetectAndroidSDK.cmake:173 (ocv_detect_android_sdk_build_tools)
CMakeLists.txt:848 (include)
解决:修改ANDROID_HOME路径如下
注意:命令行需要重新打开
生成Makefile成功
--
-- General configuration for OpenCV 4.10.0 =====================================
-- Version control: unknown
--
-- Platform:
-- Timestamp: 2025-02-26T09:22:15Z
-- Host: Windows 10.0.19045 AMD64
-- Target: Android 1 aarch64
-- CMake: 3.31.2
-- CMake generator: Ninja
-- CMake build tool: G:/MSYS2/mingw64/bin/ninja.exe
-- Configuration: Release
--
-- CPU/HW features:
-- Baseline: NEON FP16
-- Dispatched code generation: NEON_DOTPROD NEON_FP16 NEON_BF16
-- requested: NEON_FP16 NEON_BF16 NEON_DOTPROD
-- NEON_DOTPROD (1 files): + NEON_DOTPROD
-- NEON_FP16 (2 files): + NEON_FP16
-- NEON_BF16 (0 files): + NEON_BF16
--
-- C/C++:
-- Built as dynamic libs?: YES
-- C++ standard: 11
-- C++ Compiler: G:/SDK/ndk/26.0.10792818/toolchains/llvm/prebuilt/windows-x86_64/bin/clang++.exe (ver 17.0.2)
-- C++ flags (Release): -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -fno-limit-debug-info -O0 -DDEBUG -D_DEBUG
-- C Compiler: G:/SDK/ndk/26.0.10792818/toolchains/llvm/prebuilt/windows-x86_64/bin/clang.exe
-- C flags (Release): -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -fno-limit-debug-info -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,--build-id=sha1 -Wl,--no-rosegment -Wl,--no-undefined-version -Wl,--fatal-warnings -Wl,--no-undefined -Qunused-arguments -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined -Wl,--gc-sections
-- Linker flags (Debug): -Wl,--build-id=sha1 -Wl,--no-rosegment -Wl,--no-undefined-version -Wl,--fatal-warnings -Wl,--no-undefined -Qunused-arguments -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies: dl m log
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo stitching ts video videoio
-- Disabled: world
-- Disabled by dependency: -
-- Unavailable: java python2 python3
-- Applications: tests perf_tests
-- Documentation: NO
-- Non-free algorithms: NO
--
-- Android NDK: G:/SDK/ndk/26.0.10792818 (ver 26.0.10792818)
-- Android ABI: arm64-v8a
-- NDK toolchain: aarch64-linux-android-clang
-- STL type: c++_shared
-- Native API level: 21
-- Android SDK: not used, projects are not built
--
-- GUI: NONE
--
-- Media I/O:
-- ZLib: z (ver 1.2.13)
-- JPEG: build-libjpeg-turbo (ver 3.0.3-70)
-- SIMD Support Request: YES
-- SIMD Support: YES
-- WEBP: build (ver encoder: 0x020f)
-- PNG: build (ver 1.6.43)
-- SIMD Support Request: YES
-- SIMD Support: YES (Arm NEON)
-- TIFF: build (ver 42 - 4.6.0)
-- JPEG 2000: build (ver 2.5.0)
-- OpenEXR: build (ver 2.3.0)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
-- PFM: YES
--
-- Video I/O:
-- MEDIANDK: YES
-- NDK Camera: NO
--
-- Parallel framework: pthreads
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Custom HAL: YES (carotene (ver 0.0.1, Auto detected))
-- Protobuf: build (3.19.1)
-- Flatbuffers: builtin/3rdparty (23.5.9)
--
-- Python (for build): G:/Python3.11/python.exe
--
-- Install to: G:/opencv-4.10.0_so/arm64-v8a_build/install
-- -----------------------------------------------------------------
--
-- Configuring done (56.9s)
-- Generating done (2.2s)
-- Build files have been written to: G:/opencv-4.10.0_so/arm64-v8a_build
安装
ninja install
安装目录 
V7a同理
其他
指定输出目录
-DCMAKE_INSTALL_PREFIX=
集成到Android Studio
目录结构如下
build_gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "com.guide.opengllib"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode rootProject.ext.versionCode
versionName rootProject.ext.versionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk {
abiFilters /*"armeabi-v7a"*/"arm64-v8a"
}
externalNativeBuild {
cmake {
cppFlags ""
// 检查是否有正确引入C++ 相关的库依赖,比如
arguments "-DANDROID_STL=c++_shared"
}
}
}
lintOptions {
abortOnError false
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
sourceSets {
main {
jniLibs.srcDirs = ['src/main/cpp/libs']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "androidx.appcompat:appcompat:$rootProject.ext.appcompatVersion"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation "androidx.test.espresso:espresso-core:3.2.0"
}
CmakeList.txt
cmake_minimum_required(VERSION 3.4.1)
set(libname opencv_guidecore)
add_definitions("-D__STDC_CONSTANT_MACROS")
set(OpenCVHome ${CMAKE_SOURCE_DIR}/src/main/cpp)
include_directories(${OpenCVHome}/jni/include)
# 设置 STL 库
set(ANDROID_STL c++_shared)
# 设置 OpenCV 库路径
set(OpenCV_LIB_PATH ${OpenCVHome}/libs/${ANDROID_ABI}) # 根据实际路径设置
message(STATUS "OpenCV_LIB_PATH: ${OpenCV_LIB_PATH}")
add_library(opencv_imgproc
SHARED
IMPORTED)
set_target_properties(opencv_imgproc
PROPERTIES IMPORTED_LOCATION
${OpenCV_LIB_PATH}/libopencv_imgproc.so)
add_library(opencv_core
SHARED
IMPORTED)
set_target_properties(opencv_core
PROPERTIES IMPORTED_LOCATION
${OpenCV_LIB_PATH}/libopencv_core.so)
add_library(opencv_video
SHARED
IMPORTED)
set_target_properties(opencv_video
PROPERTIES IMPORTED_LOCATION
${OpenCV_LIB_PATH}/libopencv_video.so)
add_library(opencv_imgcodecs
SHARED
IMPORTED)
set_target_properties(opencv_imgcodecs
PROPERTIES IMPORTED_LOCATION
${OpenCV_LIB_PATH}/libopencv_imgcodecs.so)
file(GLOB SRC_FILES
${OpenCVHome}/*.cpp
)
add_library( # Sets the name of the library.
${libname}
SHARED
${SRC_FILES}
)
find_library(log-lib log)
# 链接 OpenCV 的 .so 文件
target_link_libraries(
${libname}
android
${log-lib}
opencv_imgproc
opencv_core
opencv_video
opencv_imgcodecs
)
JNI源码
#include <jni.h>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp> // 引入图像处理模块
#include <opencv2/core.hpp> // 引入核心模块
#include "opencv_guidecore.h"
#include <android/log.h>
#define LOG_TAG "NativeLib"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
extern "C"
JNIEXPORT void JNICALL
Java_com_guide_opengllib_MainGlActivity_processImage(JNIEnv *env, jobject thiz, jstring input_image_path, jstring output_image_path) {
// 获取传递的图像路径字符串
const char *input_path = env->GetStringUTFChars(input_image_path, nullptr);
const char *output_path = env->GetStringUTFChars(output_image_path, nullptr);
// 使用 OpenCV 读取图像
cv::Mat image = cv::imread(input_path);
if (image.empty()) {
LOGI("Could not open or find the image!");
return;
}
// 转换为灰度图像
cv::Mat gray_image;
cv::cvtColor(image, gray_image, cv::COLOR_BGR2GRAY);
// 保存处理后的图像
cv::imwrite(output_path, gray_image);
// 释放资源
env->ReleaseStringUTFChars(input_image_path, input_path);
env->ReleaseStringUTFChars(output_image_path, output_path);
LOGI("Image processed and saved to %s", output_path);
}
Activity中
static {
System.loadLibrary("opencv_guidecore"); // 加载生成的 .so 库
}
// 声明本地方法
public native void processImage(String inputImagePath, String outputImagePath);
//实例3
findViewById(R.id.test3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
processImage("", "");
}
});
打印日志
集成第三方去噪点算法
https://github.com/Linwei-Chen/NL-means/blob/master/main.cpp