Android studio配置opencv的JNI接口,实现C++代码编程

一、新建c++项目,C++版本选C++14,在工程导入Java的包,命名为opencv

在这里插入图片描述
二、配置opencv的JNI接口,拷贝opencv所需的库文件和头文件

1)把opencv Android sdk下的OpenCV-android-sdk/sdk/native/jni/include文件夹拷贝到你的项目中src/main/cpp下面。

2)把opencv Android sdk下的OpenCV-android-sdk/sdk/native/libs文件夹拷贝到你的项目中src/main/下面。并修改名字为JniLibs。
在这里插入图片描述

三、对CMake文件进行修改,打开CMakeLists.txt文件,添加如下代码,修改的地方只有最上面和最下面两部分,其中需要注意的是,设置include文件夹的地址:include_directories( C M A K E S O U R C E D I R / i n c l u d e ) , 这 里 直 接 写 / i n c l u d e , 不 要 写 成 / s r c / m a i n / i n c l u d e 这 种 格 式 , 否 则 无 法 调 用 。 s e t t a r g e t p r o p e r t i e s ( l i b o p e n c v j a v a 4 P R O P E R T I E S I M P O R T E D L O C A T I O N ( 你 自 己 J n i L i b s 的 地 址 ) / {CMAKE_SOURCE_DIR}/include),这里直接写/include,不要写成/src/main/include这种格式,否则无法调用。 set_target_properties(libopencv_java4 PROPERTIES IMPORTED_LOCATION(你自己JniLibs的地址)/ CMAKESOURCEDIR/include)/include/src/main/includesettargetproperties(libopencvjava4PROPERTIESIMPORTEDLOCATIONJniLibs/{ANDROID_ABI}/libopencv_java4.so)
注意Java4.so的版本,我的版本为4。代码如下:

在这里插入图片描述

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.10.2)

# Declares and names the project.
# 设置include文件夹的地址
include_directories(${CMAKE_SOURCE_DIR}/include)
add_library(libopencv_java4 SHARED IMPORTED)
set_target_properties(libopencv_java4 PROPERTIES IMPORTED_LOCATION
        D:/LenovoSoftstore/Install/Android/Demo/JniDemo/app/src/main/JniLibs/${ANDROID_ABI}/libopencv_java4.so)


project("jnidemo")

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             native-lib.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

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 )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

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} )

如果实验代码中含有图片,则可在target_link_libraries中加入jnigraphics,如下:在这里插入图片描述

四、配置app的build.gradle文件,打开app的build.gradle文件,进行如下添加。
1,添加的的第一部分,在cmake中加上arguments “-DANDROID_STL=c++_shared”,如下:
cmake {
cppFlags ‘-std=c++14’
arguments “-DANDROID_STL=c++_shared”
}
2,添加的的第二部分:
ndk {
}

2,添加第三部分:
sourceSets {
}
splits {
}
3,添加的第四部分:
project.ext.versionCodes
android.applicationVariants.all {
}

整个代码:

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.example.jnidemo"
        minSdkVersion 19
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags '-std=c++14'
                arguments "-DANDROID_STL=c++_shared"
            }
        }
        ndk{
            abiFilters "armeabi-v7a", "arm64-v8a"
        }


    }

    sourceSets {
        main {

            jniLibs.srcDirs = ['libs']
        }
    }

//    packagingOptions {
//        exclude 'lib/arm64-v8a/libopencv_java4.so'
//    }

    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
        }
    }





    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    externalNativeBuild {
        cmake {
            path file('src/main/cpp/CMakeLists.txt')
            version '3.10.2'
        }
    }
    buildFeatures {
        viewBinding true
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation project(path: ':opencv')
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

注意:jniLibs.srcDirs = [‘libs’] 千万不要写为:jniLibs.srcDirs = [src/main/JniLibs’] 否则程序会报错

四、在build.gradle(:opencv)中把application换成library,然后把defaultConfig注释掉,其他的不做修改,如下:在这里插入图片描述五、这个时候请先点击Build-Make project构建一下程序。然后打开native-lib.cpp文件,这是我们要写C++代码的文件,写过C++的应该都知道.cpp文件。先试着引入一下包,输入#include <opencv2/opencv.hpp>,如果变成绿色而不是红色,那么恭喜你,配置成功了,可以开始在Android平台下用C++来开发opencv代码了。
在这里插入图片描述

在这里插入图片描述

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在 Android Studio 中使用基于 C++ 的 OpenCV,需要进行以下配置步骤: 1. 下载 OpenCV for Android 并解压缩。可以从 OpenCV 官网下载最新版本。 2. 安装 Android NDK。可以从 Android Studio 的 SDK Manager 中下载并安装。 3. 在 Android Studio 中创建一个新项目并打开 build.gradle 文件。 4. 在 build.gradle 文件的 android 节点中添加以下代码: ```gradle externalNativeBuild { cmake { cppFlags "" abiFilters "" } } ``` 5. 在 build.gradle 文件的 defaultConfig 节点中添加以下代码: ```gradle externalNativeBuild { cmake { path "CMakeLists.txt" } } ``` 6. 在项目目录下创建一个 CMakeLists.txt 文件,并添加以下代码: ```cmake cmake_minimum_required(VERSION 3.4.1) add_library( native-lib SHARED native-lib.cpp ) find_library( log-lib log ) target_link_libraries( native-lib ${log-lib} ) add_library( opencv SHARED IMPORTED ) set_target_properties( opencv PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/../sdk/native/libs/${ANDROID_ABI}/libopencv_java3.so ) include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/../sdk/native/jni/include ) target_link_libraries( native-lib opencv ) ``` 7. 在 src/main 目录下创建一个 cpp 目录,并在其中添加一个 native-lib.cpp 文件。在该文件中添加以下代码: ```c++ #include <jni.h> #include <string> extern "C" JNIEXPORT jstring JNICALL Java_com_example_myapplication_MainActivity_stringFromJNI( JNIEnv* env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); } ``` 8. 在 MainActivity.java 文件中添加以下代码: ```java static { System.loadLibrary("native-lib"); System.loadLibrary("opencv"); } public native String stringFromJNI(); ``` 9. 构建并运行应用程序,如果一切配置正确,应该能够在应用程序中看到 "Hello from C++" 的输出。 以上是在 Android Studio配置基于 C++ 的 OpenCV 的步骤。需要注意的是,这只是一个简单的例子,实际使用中还需要进行更多的配置和调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值