Tutorial on OpenCV for Android with Android Studio
Hey everyone,
Welcome!
My goal with this tutorial is to make it super easy for you to create an Android application using the OpenCV library.
Before we dive in, it’s helpful to check the tool versions I used to avoid any compatibility issues.
#
Tool | Version |
---|---|
OpenCV Android SDK | openCV-3.2.0 |
Android Studio | v2.2.2 |
Android SDK Build-tools | v25 |
Android SDK Platform-tools | v25.0.3 |
Android Official NDK | android-ndk-r12b |
OS: Windows 10
First things first—download these:
C:\work\android-ndk-r12b
PATH
variable and click Editbin
folderC:\Program Files\Java\jdk1.8.0_40\bin\
C:\work\android-ndk-r12b
Let’s build your first project:
Note:
If you encounter this error:Error: NDK not configured. Download it with SDK manager.
Follow these steps:
- Go to File → Project Structure
- Set the correct NDK path under Android NDK location
{YOUR_OPENCV_SDK_DIR}\sdk\
and select the java
folder build.gradle
file and add this under dependencies
:
implementation project(':openCVLibrary320')
openCVLibrary320
is the default module name. Yours might differ depending on the SDK version.
jniLibs
Foldersrc/main/jni/
to src/main/jniLibs/
You’ll need native libraries for each processor architecture you want to support. Luckily, OpenCV provides them all!
\sdk\native\libs
inside the OpenCV SDKjniLibs
directoryPro tip: Only include the architectures you plan to support to reduce app size.
Android.mk
jniLibs
, create a new file named Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
OPENCV_LIB_TYPE := SHARED
OPENCV_CAMERA_MODULES := on
OPENCV_INSTALL_MODULES := on
include {OpenCV.mk_DIR}
LOCAL_SRC_FILES := native-lib.cpp
LOCAL_C_INCLUDES += {INCLUDE_DIR}
LOCAL_LDLIBS += -llog -ldl
LOCAL_CFLAGS += -DOPENCV_OLDER_VERSION
LOCAL_CPP_FEATURES += exceptions
LOCAL_CPPFLAGS += -fexceptions
LOCAL_MODULE := native-lib
include $(BUILD_SHARED_LIBRARY)
{OpenCV.mk_DIR}
→ path to OpenCV.mk
, usually:\sdk\native\jni\OpenCV.mk
{INCLUDE_DIR}
→ path to OpenCV’s include
directory:\sdk\native\jni\include
LOCAL_MODULE
→ name of your native C++ source file (native-lib.cpp
)Optional Configs:
OPENCV_CAMERA_MODULES
andOPENCV_INSTALL_MODULES
:
Set to off if you want the app to require the OpenCV Manager app on the user’s device
You’re now all set to start building your Android OpenCV app with native C++ support.