环境搭建
一、创建Android Studio项目
1.打开Android Studio IDE 点击 File -> New -> New Project
2.Empty Activity -> Next -> Finish
二、导入 OpenCV Android SDK 依赖项
1.File -> New -> Import Module ->OK
2.选择OpenCV4的路径(必须选择到java目录上)
例如: D:\OpenCVandroidSDK\sdk\java
3.修改模板名称
Next -> Finish
三、修改build.gradle文件
-
apply plugin: 'com.android.application'修改为apply plugin: 'com.android.library'
1.1选择build.gradle(OpenCV4)
1.2将apply plugin: 'com.android.application'修改为apply plugin: 'com.android.library'
2.将文件中的自动生成的applicationId "org.opencv"删除,因为OpenCV4模块是属于library而不是application
3.将compileSdkVersion 、buildToolsVersion、minSdkVersion 、targetSdkVersion 属性值的设置与app对应的build.gradle文件的配置一致。
4.添加jniLibs文件夹
1.在 app -> src -> main 文件夹下添加jniLibs
1.1 File -> New -> directory
1.2 app目录如下
1.3将OpenCVandroidSDK\sdk\native\libs内的架构文件复制到jniLibs中
4.配置app中的build.gradle进行配置,增加jniLibs.srcDirs参数
sourceSets{
main{
jniLibs.srcDirs = ['src/main/jniLibs']
}
}
5.配置支持的ndk类型,把架构包写到app对应的build.gradle中
ndk{
abiFilters "arm64-v8a","armeabi-v7a","x86","x86_64"
}
6.OpenCV4 build.gradle
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
defaultConfig {
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
7.app build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
defaultConfig {
applicationId "com.example.opencvdemo"
minSdkVersion 28
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk{
abiFilters "arm64-v8a","armeabi-v7a","x86","x86_64"
}
}
sourceSets{
main{
jniLibs.srcDirs = ['src/main/jniLibs']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
五、添加依赖
1.File -> Project Structure ->Dependencies -> app -> + -> 勾选OpenCV4 -> Ok->OK
六、测试