Linking C++ OpenCV to an app in Android Studio

Viewed 348

I am integrating existing C++ code that uses OpenCV to an Android app, using Android studio. For this purpose, I have installed the package OpenCV-android-sdk and added it as a module to Android studio. I have also created a simple Kotlin app.

So far I have managed to integrate my C++ code into the project. After adding the paths to the OpenCV includes by means of an include_directories statement, the code compiles successfully.

My next step would be to link against the precompiled OpenCV library, to resolve the "undefined symbol" errors. I have no idea how to achieve this/where to specify it. I have tried to find resources on the web, but not two resources tell the same and the solutions seem overly complicated. I am lost in the jungle.

1 Answers

I finally managed. Here comes the recipe (validated under Windows).

Make sure to download the OpenCV Android SDK and copy it somewhere.

The project must be created as a Native C++ app (Phone and tablet). A cpp folder is automatically created with a native-lib.cpp source file and a CMakeLists.txt.

Add the following lines to the CMakeLists file, after the project line:

set(OpenCV_DIR $ENV{OPENCV_ANDROID}/sdk/native/jni)
find_package(OpenCV REQUIRED)

You must define the environment variable OPENCV_ANDROID and make it point to the folder .../OpenCV-android-sdk that you copied. (Alternatively, you can hard-code the path in the set command.)

Then insert at the bottom

target_link_libraries(app_name ${OpenCV_LIBS})

where OpenCV_LIBS points to the folder .../OpenCV-android-sdk/sdk/native/libs, and app_name is the name you gave when creating your app.

Finally, cross fingers and build.

Related