This is a note on how to use OpencV in Android.

Documents to be prepared:

Download the Android SDK of the corresponding version from the Android Studio OpencV official website

Step one

Using an existing C++ project seems to be the fastest way to build an NDK project

Step 2

Copy the dynamic link library in opencv-Android-sdk SDK native libs to your project’s \app\libs or \app\ SRC \main\ CPP \libs\

Step 3

Put all header files under Opencv-Android-sdk SDK native jni include in your project \app SRC \main\ CPP \

Step 4

Configuration gradle

android { ... defaultConfig { ... ExternalNativeBuild {cmake {cppFlags "" abiFilters 'arm64-v8a' arguments "-dandroid_stl =c++_shared"// this is important}}... } sourceSets { main { jniLibs.srcDirs = ['libs'] //jniLibs.srcDirs = ['src/main/cpp/libs'] } } compileOptions { VERSION_1_8 targetCompatibility JavUncomfortable.VERSION_1_8} buildToolsVersion '28.0.3' NdkVersion '22.1.7171670'} Dependencies {... implementation fileTree(dir: 'libs', include: ['*.jar']) ... }Copy the code

Step 5

Modify CMakeLists. TXT

Set (${CMAKE_CXX_FLAGS} -l ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}") find_library(log-lib log ) target_link_libraries( native-lib android opencv_java4 ${log-lib} )Copy the code

Step 6

At this point, the project has basically configured the OpencV environment, and then you can write a demo to verify that the configuration environment has been properly configured.

C + + code

#include <jni.h>
#include <string>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

extern "C" JNIEXPORT jstring JNICALL
Java_cn_ololee_myopencvhelloworld_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    string hello = "File has been saved to";
    char* result=new char[100];
    string opencvOutPath="/sdcard/img_gray.jpg";
    Mat mat=imread("/sdcard/img.jpg");
    Mat grayMat;
    cvtColor(mat,grayMat,COLOR_BGR2GRAY);
    imwrite(opencvOutPath,grayMat);
    strcat(result,hello.c_str());
    strcat(result,opencvOutPath.c_str());
    jstring return_str=env->NewStringUTF(result);
    delete result;
    return return_str;
}
Copy the code

Don’t forget to apply for access to external storage in the Manifest and dynamically apply for access to files in the activity

My Gitee project:

Gitee.com/ololee/open…