Setup OpenCV and Android Studio with NDK sup­port

In this tu­to­r­ial, I’ll walk you through con­fig­ur­ing the renowned com­puter vi­sion li­brary, OpenCV, with Android Studio (version 3.0.1 at the time of writ­ing). Let’s dive in. The pre­com­piled OpenCV build for Android is avail­able at the OpenCV Homepage. Download and ex­tract it. Note that to test the ap­pli­ca­tion prop­erly on mo­bile de­vices, you’ll need to in­stall the OpenCV Manager.

In a fu­ture tu­to­r­ial, I’ll cover how to com­pile your own OpenCV li­brary and in­te­grate it with Android Studio, since the pre­com­piled dis­tri­b­u­tion omits some in­ter­est­ing and im­por­tant com­po­nents—namely SIFT fea­tures and other patent-en­cum­bered 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 mir­ror the setup for stan­dard ap­pli­ca­tions, so I’ll skip them here. When the IDE prompts for C++ set­tings, I rec­om­mend C++14 over C++11 and en­abling both Exception Support and Runtime Type Information Support (RTTI).

  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

To help CMake prop­erly de­tect OpenCV, add the fol­low­ing con­fig­u­ra­tion to your 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. Add lib_opencv to the ar­gu­ments of target_link_libraries (typically the last com­mand in CMakeLists.txt).

Note that CMake paths use for­ward slashes (/) on 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']
    }

}

Rebuild the pro­ject, and you’re all set. In up­com­ing tu­to­ri­als, I’ll demonstrate sev­eral tech­niques for work­ing with the li­brary on Android:

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