How to Integrate Opencv 4.0 into a Pure C++ Android Ndk Project

How can I integrate OpenCV 4.0 into a pure C++ Android NDK project?

  1. Download opencv Android package (e.g. opencv-4.0.1-android-sdk) and unpack to, say, ~/android.

  2. To the bottom of CMakeLists.txt, add

    set( OpenCV_DIR "~/android/OpenCV-android-sdk/sdk/native/jni" )
    find_package( OpenCV REQUIRED )
    target_link_libraries(game opencv_java)

The package will define the following variables:

OpenCV_LIBS : The list of all imported targets for OpenCV modules.

OpenCV_INCLUDE_DIRS : The list of OpenCV include directories. With CMake >= 2.8.11 you don't even need to write

include_directories(${OpenCV_INCLUDE_DIRS})

This version of prebuilt OpenCV SDK defines also

OpenCV_VERSION : The version of this OpenCV build: "4.0.1"

OpenCV_ANDROID_NATIVE_API_LEVEL : Minimum required level of Android API: "16".

This means that your app manifest needs minSdkVersion 16 or higher (the original sample needs a fix here).

Instead of the shared library that contains all OpenCV functionality, you can use static libraries (opencv_imgcodecs, opencv_stitching, et al). These static libraries assume the default ANDROID_STL=c++_static.

For best results, use NDK r.18 or r.19.

UPDATE: NDK r.21 works well for opencv 4.3.0.

Adding OpenCV to Native C code through CMake on Android Studio

UPDATE 21-Oct-19: Deprecated Git/Simpler Way in favor of new AndroidOpenCVGradlePlugin

UPDATE 22-May-18: Added missing step number 6.

UPDATE 10-May-17: New solution provides proper integration of OpenCV into application with CMake and Android Gradle plugin 2.3.1. Tested using Android Studio 2.3.1.

UPDATE 11-May-17: An additional solution has been provided

There are two ways of including OpenCV.

Using AndroidOpenCVGradlePlugin

Visit https://github.com/ahasbini/AndroidOpenCVGradlePlugin for more details.

Git/Simpler Way

Visit https://github.com/ahasbini/Android-OpenCV for more details.

Manual/Advanced Way

To include OpenCV libraries into Android Studio Project, its best to create a new Library Module in the project and port the files from OpenCV Android SDK bundle into it:

  1. Create a new module by selecting File>New Module.
  2. Select "Android Library", and then enter the details:

    • Library name: OpenCV
    • Module name: opencv
    • Package name: org.opencv
  3. Once the new module created, copy the contents of path_to_opencv_sdk/sdk/java/src directory into path_to_your_project/opencv/src/main/java.
  4. Under main, create the following directly path: aidl/org/opencv/engine and move main/java/org/opencv/engine/OpenCVEngineInterface.aidl into it.
  5. Copy the contents of path_to_opencv_sdk/sdk/java/res into path_to_your_project/opencv/src/main/res.
  6. Create sdk folder inside path_to_your_project/opencv/src/ and copy path_to_opencv_sdk/sdk/native folder into it.
  7. Within the opencv module, create CMakeLists.txt file and add the following lines in the following order:

cmake_minimum_required(VERSION 3.4.1)
set(OpenCV_DIR "src/sdk/native/jni")
find_package(OpenCV REQUIRED)
message(STATUS "OpenCV libraries: ${OpenCV_LIBS}")
include_directories(${OpenCV_INCLUDE_DIRS})


  1. Within the opencv module, edit the build.gradle file as such:

...
android {
...

defaultConfig {
minSdkVersion 8
targetSdkVersion 25
versionCode 3200
versionName "3.2.0"

...

externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
}
}
}
buildTypes {
...
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
sourceSets {
main {
jni.srcDirs = [jni.srcDirs, 'src/sdk/native/jni/include']
jniLibs.srcDirs = [jniLibs.srcDirs, 'src/sdk/native/3rdparty/libs', 'src/sdk/native/libs']
}
}
}
...


  1. Within the app (application module, could be another name) module, create/edit CMakeLists.txt file and add the following lines in the following order (Note the different path set to OpenCV_DIR):

set(OpenCV_DIR "../opencv/src/sdk/native/jni")
find_package(OpenCV REQUIRED)
message(STATUS "OpenCV libraries: ${OpenCV_LIBS}")
target_link_libraries(YOUR_TARGET_LIB ${OpenCV_LIBS})


  1. Within the app (application module, could be another name) module, edit the build.gradle file as such:

...    
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
}
}
buildTypes {
...
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}

dependencies {
...
compile project(':opencv')
}


  1. Do a gradle sync, and now the OpenCV native libs, header files and Java wrapper classes are included.

When project is built and apk is launched, you could inspect the packaged apk under path_to_project/path_to_app_module/build/output/ (drag the apk onto the text editor tabs of Android Studio)

APK Inspection

You should see a libopencv_java3.so under each abi architecture folder.

Initialize the OpenCV SDK in your java class :

public class MyClass {

static {
if (BuildConfig.DEBUG) {
OpenCVLoader.initDebug();
}
}

...
}

And you should see within logcat messages specifying the OpenCV has been loaded (the first error is normal):

05-10 10:42:31.451 D/OpenCV/StaticHelper: Trying to get library list
05-10 10:42:31.452 E/OpenCV/StaticHelper: OpenCV error: Cannot load info library for OpenCV
05-10 10:42:31.452 D/OpenCV/StaticHelper: Library list: ""
05-10 10:42:31.452 D/OpenCV/StaticHelper: First attempt to load libs
05-10 10:42:31.452 D/OpenCV/StaticHelper: Trying to init OpenCV libs
05-10 10:42:31.452 D/OpenCV/StaticHelper: Trying to load library opencv_java3
05-10 10:42:32.031 D/OpenCV/StaticHelper: Library opencv_java3 loaded
05-10 10:42:32.031 D/OpenCV/StaticHelper: First attempt to load libs is OK
05-10 10:42:32.045 I/OpenCV/StaticHelper: General configuration for OpenCV 3.2.0 =====================================
05-10 10:42:32.045 I/OpenCV/StaticHelper: Version control: 3.2.0
05-10 10:42:32.045 I/OpenCV/StaticHelper: Platform:
05-10 10:42:32.045 I/OpenCV/StaticHelper: Timestamp: 2016-12-23T13:04:49Z
05-10 10:42:32.045 I/OpenCV/StaticHelper: Host: Linux 4.8.0-25-generic x86_64
05-10 10:42:32.045 I/OpenCV/StaticHelper: Target: Linux 1 x86_64
05-10 10:42:32.045 I/OpenCV/StaticHelper: CMake: 2.8.12.2
05-10 10:42:32.045 I/OpenCV/StaticHelper: CMake generator: Ninja
05-10 10:42:32.045 I/OpenCV/StaticHelper: CMake build tool: /usr/bin/ninja
05-10 10:42:32.045 I/OpenCV/StaticHelper: Configuration: Release
05-10 10:42:32.045 I/OpenCV/StaticHelper: C/C++:
05-10 10:42:32.045 I/OpenCV/StaticHelper: Built as dynamic libs?: NO
05-10 10:42:32.045 I/OpenCV/StaticHelper: C++ Compiler: /usr/bin/ccache /opt/android/android-ndk-r10e/toolchains/x86_64-4.9/prebuilt/linux-x86_64/bin/x86_64-linux-android-g++ (ver 4.9)

Linking errors on Android with OpenCV 3.4.0 and NDK

Recently, NDK switched to libc++ as default STL, but OpenCV is built with gnustl.

externalNativeBuild {
cmake {
arguments "-DANDROID_STL=gnustl_shared"
}
}

for your library will fix that.

Alternatively, you can rebuild OpenCV with c++_shared.

Update: Good news! You can simply download OpenCV 4.0.1 and it will work smoothly with NDK r.18+.

Android Studio NDK being incompatible though having been set properly

The Issue I had was not with the NDK tool , it was with the directory where i had placed it.

There was space between file name which resulted in the error eg"User space Name".eg:C:/User/Elon Musk/SDK/ndk

I rectified this mistake of mine after a warning display by Android Studio lint .

I changed the Android SDK directory placement and rerun the code and the issue got resolved.

As per the answer above by Lakindu , there is no need for downgrading the Ndk library just make sure that the NDK is in the right place .

And also dont forget to add the NDK tool in the Project Structure which you can find by clicking Ctrl + Shift +Alt + S simultaneously.

OpenCV in Android Studio

The below steps for using Android OpenCV sdk in Android Studio. This is a simplified version of this SO answer.

  1. Download latest OpenCV sdk for Android from OpenCV.org and decompress the zip file.
  2. Import OpenCV to Android Studio, From File -> New -> Import Module, choose sdk/java folder in the unzipped opencv archive.
  3. Update build.gradle under imported OpenCV module to update 4 fields to match your project build.gradle a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and d) targetSdkVersion.
  4. Add module dependency by Application -> Module Settings, and select the Dependencies tab. Click + icon at bottom, choose Module Dependency and select the imported OpenCV module.
    • For Android Studio v1.2.2, to access to Module Settings :
      in the project view, right-click the dependent module
      -> Open Module Settings
  5. Copy libs folder under sdk/native to Android Studio under app/src/main.
  6. In Android Studio, rename the copied libs directory to jniLibs and we are done.

Step (6) is since Android studio expects native libs in app/src/main/jniLibs instead of older libs folder. For those new to Android OpenCV, don't miss below steps

  • include static{ System.loadLibrary("opencv_java"); } (Note: for OpenCV version 3 at this step you should instead load the library opencv_java3.)
  • For step(5), if you ignore any platform libs like x86, make sure your device/emulator is not on that platform.

OpenCV written is in C/C++. Java wrappers are

  1. Android OpenCV SDK - OpenCV.org maintained Android Java wrapper. I suggest this one.
  2. OpenCV Java - OpenCV.org maintained auto generated desktop Java wrapper.
  3. JavaCV - Popular Java wrapper maintained by independent developer(s). Not Android specific. This library might get out of sync with OpenCV newer versions.


Related Topics



Leave a reply



Submit