Setup OpenCV and Android Studio with NDK support
In this tutorial, I’ll walk you through configuring the renowned computer vision library, OpenCV, with Android Studio (version 3.0.1 at the time of writing). Let’s dive in. The precompiled OpenCV build for Android is available at the OpenCV Homepage. Download and extract it. Note that to test the application properly on mobile devices, you’ll need to install the OpenCV Manager.
In a future tutorial, I’ll cover how to compile your own OpenCV library and integrate it with Android Studio, since the precompiled distribution omits some interesting and important components—namely SIFT features and other patent-encumbered 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.

The next two steps mirror the setup for standard applications, so I’ll skip them here. When the IDE prompts for C++ settings, I recommend C++14 over C++11 and enabling both Exception Support and Runtime Type Information Support (RTTI).
-
From the Project Structure windows (
File -> Project Structure), we add the OpenCV module by clicking on the plus sign, selecting theImport Eclipse ADT Projectand pointing to the/path/to/OpenCV4Android/sdk/javadirectory. -
Select
Modules -> app. In theDependenciestab, add the OpenCV module by selecting the plus sign.Module Dependency.- Select
:openCVLibrary340.

Configure CMAKE and NDK
To help CMake properly detect OpenCV, add the following configuration
to your CMakeLists.txt:
- 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)
- Add
lib_opencvto the arguments oftarget_link_libraries(typically the last command inCMakeLists.txt).
Note that CMake paths use forward slashes (/) on both Windows and Linux.
Configure Gradle
-
Put
abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'mips', 'mips64'in thecmakesetting. -
Put the following text inside
android:
sourceSets {
main {
jni.srcDirs = ['src/main/cpp']
jniLibs.srcDirs = ['\path\to\OpenCV-android-sdk\\sdk\\native\\libs']
}
}
Rebuild the project, and you’re all set. In upcoming tutorials, I’ll demonstrate several techniques for working with the library on Android:
- Transfer OpenCV MAT from Android to NDK code.
- Organize the project and source code.