1.下载opencv Android版本
2.解压导入android studio,我这里是先导入低版本的,还是gradle,直接导入module,我这里是4.2.0的版本
我的as版本是Android Studio Electric Eel 2022.1.1 Patch 2,我导入直接就能用
//load OpenCV engine and init OpenCV library
//这里放在oncreate里面用作初始化if (!OpenCVLoader.initDebug()){OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_2_0,this,mLoaderCallback);}else{mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);}//OpenCV库加载并初始化成功后的回调函数private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {@Overridepublic void onManagerConnected(int status) {// TODO Auto-generated method stubswitch (status){case BaseLoaderCallback.SUCCESS:Log.e(TAG, "openCv=================成功加载");break;default:super.onManagerConnected(status);Log.e(TAG, "openCv=================加载失败");break;}}};
3.改造成build.gradle.kts版本使用
1.把代码从低版本android studio直接复制到高版本的android studio里面,这里我改了个名字,为了比较直观,我直接复制了两份用来做对比
2.直接对比改造
原版本
apply plugin: 'com.android.library'println "OpenCV: " + project.buildscript.sourceFileandroid {compileSdkVersion 32//buildToolsVersion "x.y.z" // not needed since com.android.tools.build:gradle:3.0.0defaultConfig {minSdkVersion 25targetSdkVersion 32externalNativeBuild {cmake {arguments "-DANDROID_STL=c++_shared"targets "opencv_jni_shared"}}}buildTypes {debug {packagingOptions {// doNotStrip '**/*.so' // controlled by OpenCV CMake scripts}}release {packagingOptions {// doNotStrip '**/*.so' // controlled by OpenCV CMake scripts}minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'}}compileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}sourceSets {main {jniLibs.srcDirs = ['native/libs']java.srcDirs = ['java/src']aidl.srcDirs = ['java/src']res.srcDirs = ['java/res']manifest.srcFile 'java/AndroidManifest.xml'}}externalNativeBuild {cmake {path (project.projectDir.toString() + '/libcxx_helper/CMakeLists.txt')}}}dependencies {
}
改造以后的版本
plugins {id("com.android.library")
}println("OpenCV: " + project.buildscript.sourceFile)android {compileSdk = 32defaultConfig {namespace = "org.opencv"minSdk = 25testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"consumerProguardFiles("consumer-rules.pro")externalNativeBuild {cmake {arguments.add("-DANDROID_STL=c++_shared")targets.add("opencv_jni_shared")}}}compileOptions {sourceCompatibility = JavaVersion.VERSION_1_8targetCompatibility = JavaVersion.VERSION_1_8}sourceSets {getByName("main") {jniLibs.srcDirs("native/libs")java.srcDirs("java/src")aidl.srcDirs("java/src")res.srcDirs("java/res")manifest.srcFile("java/AndroidManifest.xml")}}externalNativeBuild {cmake {path = file("${project.projectDir}/libcxx_helper/CMakeLists.txt")}}buildFeatures{aidl = true}}dependencies {}
因为新kts的一些特性,我们新增了
(1).namespace = "org.opencv" (2).buildFeatures{aidl = true }