opencv OpenCV initialization in Android Static Initialization


Example

According to this approach all OpenCV binaries are included into your application package. It is designed mostly for development and debugging purposes. This approach is deprecated for the production code, async initialization is recommended.

If your application project doesn’t have a JNI part, just copy the corresponding OpenCV native libs from OpenCV-3.1.0-android-sdk/sdk/native/libs to your project directory to folder app/src/main/jniLibs.

In case of the application project with a JNI part, instead of manual libraries copying you need to modify your Android.mk file: add the following two code lines after the "include $(CLEAR_VARS)" and before "include path_to_OpenCV-3.1.0-android-sdk/sdk/native/jni/OpenCV.mk":

OPENCV_CAMERA_MODULES:=on
OPENCV_INSTALL_MODULES:=on

The result should look like the following:

include $(CLEAR_VARS)
# OpenCV
OPENCV_CAMERA_MODULES:=on
OPENCV_INSTALL_MODULES:=on
include ../../sdk/native/jni/OpenCV.mk

After that the OpenCV libraries will be copied to your application jniLibs folder during the JNI build.

The last step of enabling OpenCV in your application is Java initialization code before calling OpenCV API. It can be done, for example, in the static section of the Activity class:

static {
    if (!OpenCVLoader.initDebug()) {
        // Handle initialization error
    }
}

If you application includes other OpenCV-dependent native libraries you should load them after OpenCV initialization:

static {
    if (!OpenCVLoader.initDebug()) {
        // Handle initialization error
    } else {
        System.loadLibrary("my_jni_lib1");
        System.loadLibrary("my_jni_lib2");
    }
}

Note: initDebug() method is deprecated for production code. It is designed for experimental and local development purposes only. If you want to publish your app use approach with async initialization.