在AndroidStudio,调用OpenCV的SDK,并在JNI层的C++代码调用opencv

在AndroidStudio,调用OpenCV的SDK,并在JNI层的C++代码调用opencv,第1张

1、新建native C++项目
2、因为android studio版本不同,如有【Include C++ support】选项,可以勾选
3、下载android版opencv的sdk
下载地址
4、将 \opencv-4.5.5-android-sdk\OpenCV-android-sdk\sdk\native\jni中的各种架构(如图)的opencv的sdk放入src/main/cpp/libs中
5、
5、CMakeList.txt

# 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.18.1)

# Declares and names the project.

project("myapplication2")


set(CMAKE_VERBOSE_MAKEFILE on)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")

#set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake-modules)
#set(pathToOpenCv C:/Users/63038/Desktop/opencv-4.5.5-android-sdk/OpenCV-android-sdk/sdk/native/jni)
set(pathToOpenCv C:/Users/63038/Desktop/opencv-4.5.5-android-sdk/OpenCV-android-sdk/)
#find_package(OpenCV REQUIRED )
#if(OpenCV_FOUND)
#    include_directories(${OpenCV_INCLUDE_DIRS})
#    message(STATUS "OpenCV library status:")
#    message(STATUS "    version: ${OpenCV_VERSION}")
#    message(STATUS "    libraries: ${OpenCV_LIBS}")
#    message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")
#else(OpenCV_FOUND)
#    message(FATAL_ERROR "OpenCV library not found")
#endif(OpenCV_FOUND)


include_directories(${pathToOpenCv}/sdk/native/jni/include)

add_library(lib_opencv STATIC IMPORTED )
set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION ${PROJECT_SOURCE_DIR}/libs/${ANDROID_ABI}/libopencv_java4.so )

# 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.
        myapplication2

        # 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.
        myapplication2

        # Links the target library to the log library
        # included in the NDK.
        ${log-lib} android -ljnigraphics lib_opencv
#        ${OpenCV_LIBS}
        )

6、build.gradle

plugins {
    id 'com.android.application'
}

android {
//    sourceSets.main.jniLibs.srcDirs = ['libs']


    compileSdk 32

    defaultConfig {
        applicationId "com.example.myapplication2"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11 -frtti -fexceptions'
                abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
                arguments "-DANDROID_STL=c++_shared"
            }
        }
    }

    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.18.1'
//            arguments "-DANDROID_STL=c++_shared"
        }
    }
//    dataBinding {
//        enable=true
//    }
    buildFeatures {
        viewBinding true
    }
}


dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.2'
//    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
//    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

6、native-lib.cpp

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include "opencv2/imgproc.hpp"
using namespace cv;
using namespace std;
extern "C" {
JNIEXPORT jstring JNICALL Java_com_example_myapplication2_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

// 注意这里的函数名格式:Java_各级包名_类名_函数名(参数...),需严格按照这种格式,否则会出错
JNIEXPORT jintArray JNICALL Java_com_example_myapplication2_MainActivity_gray(
        JNIEnv *env,
        jobject instance,
        jintArray buf,
        jint w,
        jint h) {
    jint *cbuf = env->GetIntArrayElements(buf, JNI_FALSE);
    if (cbuf == NULL) { return 0; }
    cv::Mat imgData(h, w, CV_8UC4, (unsigned char *) cbuf);
    uchar *ptr = imgData.ptr(0);
    for (int i = 0; i < w * h; i++) {
        //计算公式:Y(亮度) = 0.299*R + 0.587*G + 0.114*B
        // 对于一个int四字节,其彩色值存储方式为:BGRA
        int grayScale = (int) (ptr[4 * i + 2] * 0.299 + ptr[4 * i + 1] * 0.587 +
                               ptr[4 * i + 0] * 0.114);
        ptr[4 * i + 1] = grayScale;
        ptr[4 * i + 2] = grayScale;
        ptr[4 * i + 0] = grayScale;
    }
    int size = w * h;
    jintArray result = env->NewIntArray(size);
    env->SetIntArrayRegion(result, 0, size, cbuf);
    env->ReleaseIntArrayElements(buf, cbuf, 0);
    return result;
}


}

7、MainActivity.java

package com.example.myapplication2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.myapplication2.databinding.ActivityMainBinding;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'myapplication2' library on application startup.
    static {
        System.loadLibrary("myapplication2");
        System.out.println(System.getProperty("java.library.path"));
    }

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable( R.drawable.pic)).getBitmap();
        int w = bitmap.getWidth(), h = bitmap.getHeight();
        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);
        int [] resultPixes=gray(pix,w,h);
        Bitmap result = Bitmap.createBitmap(w,h, Bitmap.Config.RGB_565);
        result.setPixels(resultPixes, 0, w, 0, 0,w, h);
        ImageView img = (ImageView)findViewById(R.id.img2);
        img.setImageBitmap(result);
        System.out.println(stringFromJNI());
    }

    /**
     * A native method that is implemented by the 'myapplication2' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
    public native int[] gray(int[] buf, int w, int h);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/789111.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存