android studio configure build报错_Android 接入opencvcmake的方式

0e0bb9cb00e878e11e9d2d592ee6af67.png

秦子帅 明确目标,每天进步一点点..... 894814d2350bbec873bdde6b5971df33.png
作者 |  Mp5A5 地址 |  www.jianshu.com/p/410422e8d8d2

简述

最近通过Java sdk的方式已经将opencv接入到项目中了,如果想使用opencv sdk 提供的 C++ 头文件与 .so动态库,自己封装jni这样使用上篇的方式显然是不能实现的。所以本篇我们介绍通过cmake的方式接入opencv。显示效果:

d33c974fa020a3c559158cb75067388c.gif

接入步骤

1、新建jni项目

c40ae4681574d67ea1e17bcc0ad07d3a.png


具体创建过程参考这篇文章:https://www.jianshu.com/p/af430ae13ecd

2、导入so库

在项目app/src/main目录下新建jniLibs,并将解压后的opencv sdk 目录下对应的路径 sdk/native/libs 中的文件复制到jniLibs中。

93a38dc034c4e9669e50cac808ad8d23.png
9b3e06c966d705b7a56f4570bcb128a9.png

2、导入cpp文件

将opencv sdk 目录下对应的路径 sdk/native/jni/include 中的文件复制到cpp目录中。

74bc97ea59b848d70dcecb9db0ff6b07.png
1d532b2665a6a38d3be9b9935c455638.png

3、修改CMakeLists

  1. 将src/main/cpp 中的CMakeLists移动到app目录下。

e31dff3d3e0b22d297eb0bfdfb30fd78.png

2.修改CMakeLists中的内容

# For more information about using CMake with Android Studio, read the# documentation: https://d.android.com/studio/projects/add-native-code.html# 设置CMAKE的版本号
cmake_minimum_required(VERSION 3.4.1)# 设置include文件夹的地址
include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include)# 设置opencv的动态库
add_library(libopencv_java4 SHARED IMPORTED)
set_target_properties(libopencv_java4 PROPERTIES IMPORTED_LOCATION${CMAKE_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java4.so)
add_library( # Sets the name of the library.
        native-lib #.so库名 可自定义# Sets the library as a shared library.
        SHARED# Provides a relative path to your source file(s).
        src/main/cpp/native-lib.cpp)
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.
        native-lib
        libopencv_java4# Links the target library to the log library# included in the NDK.${log-lib})

  1. 修改app 中的build.gradle文件

  • defaultConfig 中配置cmake和ndk

externalNativeBuild {cmake {cppFlags "-std=c++11"
           arguments "-DANDROID_STL=c++_shared"
       }
}
ndk{abiFilters "armeabi-v7a","arm64-v8a"
}

  • android 中配置jniLibs

sourceSets{
     main{
         jniLibs.srcDirs = ['src/main/jniLibs']
     }
}

  1. android 中配置cmake和ndk相关

externalNativeBuild {cmake {path file('CMakeLists.txt')
            version "3.10.2"
        }
    }
splits {abi {enable true
        reset()
        include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' //select ABIs to build APKs for
        universalApk true //generate an additional APK that contains all the ABIs
    }
}
project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]
android.applicationVariants.all { variant ->
    variant.outputs.each { output ->
        output.versionCodeOverride =
                project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) * 1000000 + android.defaultConfig.versionCode
    }
}

如果是老项目则不必配置splits否则会报错,只需要干掉下面的代码

splits {
    abi {
        enable true
        reset()include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' //select ABIs to build APKs for
        universalApk true //generate an additional APK that contains all the ABIs
    }
}

最终配置完的代码为:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "com.jd.opencv"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11"
                arguments "-DANDROID_STL=c++_shared"
            }
        }
        ndk{
            abiFilters "armeabi-v7a","arm64-v8a"
        }
    }
    sourceSets{
        main{
            jniLibs.srcDirs = ['src/main/jniLibs']
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path file('CMakeLists.txt')
            version "3.10.2"
        }
    }
    splits {
        abi {
            enable true
            reset()include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' //select ABIs to build APKs for
            universalApk true //generate an additional APK that contains all the ABIs
        }
    }
    project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]
    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
                    project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) * 1000000 + android.defaultConfig.versionCode
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

使用

我们将一张彩色图片通过 opencv 处理成一张灰色的照片。

1、编写处理照片的代码。

  • 创建native代码

object NativeLibUtils{
    init {
        System.loadLibrary("native-lib")
    }
    external fun bitmap2Grey(pixels: IntArray, w: Int, h: Int): IntArray
}

  • 创建 jni 代码

#include #include #include #include#include#include #include using namespace cv;using namespace std;extern "C"JNIEXPORT jintArray JNICALLJava_com_mp5a5_opencv_NativeLibUtils_bitmap2Gray(JNIEnv *env, jobject instance, jintArray pixels,
                                                 jint w, jint h) {
    jint *cur_array;
    jboolean isCopy = static_cast(false);
    cur_array = env->GetIntArrayElements(pixels, &isCopy);if (cur_array == NULL) {return 0;
    }Mat img(h, w, CV_8UC4, (unsigned char *) cur_array);
    cvtColor(img, img, CV_BGRA2GRAY);
    cvtColor(img, img, CV_GRAY2BGRA);int size = w * h;
    jintArray result = env->NewIntArray(size);
    env->SetIntArrayRegion(result, 0, size, (jint *) img.data);
    env->ReleaseIntArrayElements(pixels, cur_array, 0);return result;
}

  • 调用 native 代码来实现彩色图片转换成灰色图片

private fun showGrayImg() {val w = bitmap.widthval h = bitmap.heightval pixels = IntArray(w * h)
    bitmap.getPixels(pixels, 0, w, 0, 0, w, h)val resultData: IntArray = NativeLibUtils.bitmap2Gray(pixels, w, h)val resultImage = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
    resultImage.setPixels(resultData, 0, w, 0, 0, w, h)
    iv_image.setImageBitmap(resultImage)
}

  • 完整转换的代码

class OpenCvActivity : AppCompatActivity(), View.OnClickListener {private lateinit var bitmap: Bitmapoverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_opencv)
        bitmap = BitmapFactory.decodeResource(resources, R.mipmap.person)
        iv_image.setImageBitmap(bitmap)
        btn_btn1.setOnClickListener(this)
        btn_btn2.setOnClickListener(this)
    }override fun onClick(v: View?) {
        v?.id?.let {when (it) {
                R.id.btn_btn1 -> {
                    showGrayImg()
                }
                R.id.btn_btn2 -> {
                    showRgbImg()
                }
            }
        }
    }private fun showRgbImg() {
        bitmap = BitmapFactory.decodeResource(resources, R.mipmap.person)
        iv_image.setImageBitmap(bitmap)
    }private fun showGrayImg() {val w = bitmap.widthval h = bitmap.heightval pixels = IntArray(w * h)
        bitmap.getPixels(pixels, 0, w, 0, 0, w, h)val resultData: IntArray = NativeLibUtils.bitmap2Gray(pixels, w, h)val resultImage = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        resultImage.setPixels(resultData, 0, w, 0, 0, w, h)
        iv_image.setImageBitmap(resultImage)
    }
}

<?xml  version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><ImageViewandroid:id="@+id/iv_image"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_above="@id/ll_location"app:srcCompat="@mipmap/person" /><LinearLayoutandroid:id="@+id/ll_location"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_btn1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="灰度图" /><Buttonandroid:id="@+id/btn_btn2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="色图" />LinearLayout>RelativeLayout>

Demo 的 Github 地址https://github.com/Mp5A5/AndroidOpenCv

感兴趣的在看f4ecea1760f4442f39c4ff13be103f7b.gif走一波哦

---END---

f6338a9caf4a58901d52b5000181983e.png转发至朋友圈,是绝对的真爱

48eec3c1120ec93a58d2ff91f152af8f.png 你点的每个好看,我都认真当成了喜欢
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值