Setup OpenCV and Android Studio with NDK support

In this tutorial, I will demonstrate how to configurate the renowned computer vision libary, OpenCV, with the current Android Studio version (3.0.1). Let get started. The compiled version of OpenCV which supports Android is available at OpenCV Homepage. Download and extract it. Please note that to test the application properly on the mobile devices, the OpenCV Manager has to be installed.

In another tutorial, I will talk about how to compile our own OpenCV library and put it to Android Studio since the pre-compiled library misses some interesting and important components, e.g, the SIFT features and other licensed algorithms.

Creating a new Android project with NDK support

From the menu, select File->New->New Project and select Include C++ support in the Create New Project dialog.

Step 1

The next two steps are similar to the setup for normal applications, so I skip it. Later, the IDE asks the C++ settings for the project, I prefer C++14 over C++11 and also add two options, namely Exception Support and Runtime Type Information Support, for the project.

  1. From the Project Structure windows (File -> Project Structure), we add the OpenCV module by clicking on the plus sign, selecting the Import Eclipse ADT Project and pointing to the /path/to/OpenCV4Android/sdk/java directory.

  2. Select Modules -> app. In the Dependencies tab, add the OpenCV module by selecting the plus sign.

    1. Module Dependency.
    2. Select :openCVLibrary340.

Add openCVLibrary340

Configurate CMAKE and NDK

In order to get CMAKE properly detect OpenCV, we add the following configuration to CMAKELists.txt:

  1. Add a new library:
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 arguments of target_link_libraries (the last command in CMakeLists.txt).

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

Configurate Gradle

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

  2. Put the following text inside android:

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

}

Build the project again and we are done. In the the couple tutorials I will demonstate several techniques to manipulate the libary on Android:

  • Transfer OpenCV MAT from Android to NDK code.
  • Organize the project and source code. -
comments powered by Disqus