Setup OpenCV and Android Studio with NDK sup­port

In this tu­to­r­ial, I will demon­strate how to con­fig­ure the renowned com­puter vi­sion li­brary, OpenCV, with the cur­rent Android Studio ver­sion (3.0.1). Let’s get started. The com­piled ver­sion of OpenCV which sup­ports Android is avail­able at OpenCV Homepage. Download and ex­tract it. Please note that to test the ap­pli­ca­tion prop­erly on the mo­bile de­vices, the OpenCV Manager has to be in­stalled.

In an­other tu­to­r­ial, I will talk about how to com­pile our own OpenCV li­brary and put it to Android Studio since the pre-com­piled li­brary misses some in­ter­est­ing and im­por­tant com­po­nents, e.g, the SIFT fea­tures and other li­censed al­go­rithms.

Creating a new Android pro­ject with NDK sup­port

From the menu, se­lect File->New->New Project and se­lect Include C++ support in the Create New Project di­a­log.

Step 1

The next two steps are sim­i­lar to the setup for nor­mal ap­pli­ca­tions, so I skip it. Later, the IDE asks the C++ set­tings for the pro­ject, I pre­fer C++14 over C++11 and also add two op­tions, namely Exception Support and Runtime Type Information Support, for the pro­ject.

  1. From the Project Structure win­dows (File -> Project Structure), we add the OpenCV mod­ule by click­ing on the plus sign, se­lect­ing the Import Eclipse ADT Project and point­ing to the /path/to/OpenCV4Android/sdk/java di­rec­tory.

  2. Select Modules -> app. In the Dependencies tab, add the OpenCV mod­ule by se­lect­ing the plus sign.

    1. Module Dependency.
    2. Select :openCVLibrary340.

Add openCVLibrary340

Configure CMAKE and NDK

In or­der to get CMAKE prop­erly de­tect OpenCV, we add the fol­low­ing con­fig­u­ra­tion to CMakeLists.txt:

  1. Add a new li­brary:
include_directories(/path/to/OpenCV4Android/sdk/native/jni/include)
add_library( lib_opencv SHARED IMPORTED )
set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION /path/to/OpenCV4Android/sdk/native/libs/${ANDROID_ABI}/libopencv_java3.so)
  1. Put lib_opencv to the ar­gu­ments of target_link_libraries (the last com­mand in CMakeLists.txt).

Beware that the path in CMAKE use / in both Windows and Linux.

Configure Gradle

  1. Put abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'mips', 'mips64' in the cmake set­ting.

  2. Put the fol­low­ing text in­side android:

sourceSets {
    main {
        jni.srcDirs = ['src/main/cpp']
        jniLibs.srcDirs = ['\path\to\OpenCV-android-sdk\\sdk\\native\\libs']
    }

}

Build the pro­ject again and we are done. In the cou­ple of up­com­ing tu­to­ri­als I will demon­strate sev­eral tech­niques to ma­nip­u­late the li­brary on Android:

  • Transfer OpenCV MAT from Android to NDK code.
  • Organize the pro­ject and source code.