layout: post title: How to import OpenCV 4.5.2 in android studio date: 2021-04-22 00:00:00 description: tags: opencv android_studio cpp android jni categories: android opencv —
Download from https://opencv.org/releases/ and unzip it.
File > New > New Project…
File > New > Import Module…
And choose the “sdk” folder in the OpenCV SDK.
Some tutorials suggested to rename the folder before import. Don’t do that. It is because OpenCV hardcoded the path with the name of “sdk” in the native/jni/OpenCVConfig.cmake
include "opencv"
project(":opencv").projectDir = file("sdk")
1. Open the application build.gradle which is under the “app” folder.
2. Add OpenCV_DIR cmake argument under android > defaultConfig > externalNativeBuild > cmake
arguments "-DOpenCV_DIR=" + file('../sdk').absolutePath + "/native/jni",
"-DANDROID_TOOLCHAIN=clang",
"-DANDROID_STL=c++_shared"
3. Add OpenCV module dependency to application
implementation project(':opencv')
1. Open CMakeLists.txt in app/src/main/cpp
2. Add the following code to load the OpenCV package
set(ANDROID_OPENCV_COMPONENTS "opencv_java" CACHE STRING "")
message(STATUS "ANDROID_ABI=${ANDROID_ABI}")
find_package(OpenCV REQUIRED COMPONENTS ${ANDROID_OPENCV_COMPONENTS})
Link project with the library
target_link_libraries(${PROJECT_NAME} ${ANDROID_OPENCV_COMPONENTS})
And now you can import OpenCV library in JNI
and in the java.
To study how to program OpenCV, read samples in the SDK folder you have downloaded. Enjoy~