Run samples of open cv in android studio

Hi, I recently downloaded open cv for android (version 4.0.1 ), I have successfully integrated open cv with android. Now I wish to run one of the samples that are provided. I tried to do it in a different number of ways but I am still stuck. I think I am missing something. Please can anyone tell me/guide me as to how can I import the provided samples in android studio? Thanks in advance!

You need to build the project successfully with CMake. You have to set the BUILD_JAVA and ANDROID flags when configuring with CMake to get the android studio project files generated.

You also have tohave ANDROID_NDK discoverable and usable by CMake.

You seem to describe building OpenCV, not projects that use OpenCV, which here is successfully integrated. OpenCV is just a set of Android libraries in that case, just like any other libraries inside an Android Studio project.

Thanks for replying! I didn’t know about CMake, I’ll try building with it and keep the results posted here.

If you just want to use OpenCV as an android library and then try out samples, it’s easier to just copy the code. Getting the libraries build from source is more complicated.

They need to be built because build.gradle and similar files are transformed during the build process.

Yeah, I did that only, but still, I wanted to know if it was possible to build directly from them. I just thought knowing the stuff would help me broaden my understanding of file structures in Android.

If you want to build from source you can take the whole OpenCV repository:

You need to have CMake and Android-NDK. If you’re using Android Studio, it can manage NDK for you (you just go to SDK manager and you will see NDK checkbox in SDK Tools tab). NDK will be in the ANDROID_SDK_LOCATION/ndk/22.0.7026061 or a different version.

Inside opencv/ directory you can create a new dir called build/ (or any name you like).

Inside the build/ directory you can invoke the cmake command.

#!/usr/bin/env bash
export ANDROID_NDK="$ANDROID_SDK/ndk/22.0.7026061"
# android.toolchain.cmake in opencv source does not work so
# `.cmake` file included in the NDK is used.
cmake .. \
  -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK/build/cmake/android.toolchain.cmake" \

After build/ directory is configured you can just run make inside it.

After that finishes you should have a build/opencv_android directory that you can open inside Android Studio and build each separate sample and install it on your phone.

You might only need DNN or other modules that are shown in the samples and you can build only with them by adding a -DBUILD_LIST=dnn to script above.
If you don’t care about the build time you can just do a build with everything.

1 Like

Thanks for taking the effort to clarify the steps! I will definitely try out the suggested approach.