How to import OpenCV 4.5.2 in android studio
Step 1: Download OpenCV SDK
Download from https://opencv.org/releases/ and unzip it.
Step 2: Create your android project with JNI
File > New > New Project…

Step 3: Import OpenCV
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

Step 4: Edit setting.gradle
- Open setting.gradle
- Add a module with the name “opencv” and link to the folder “sdk”
include "opencv"
project(":opencv").projectDir = file("sdk")

Step 5: Edit the application build.gradle
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')

Step 6: Modify the application cmake file
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})

Final: Sync Gradle

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~
Enjoy Reading This Article?
Here are some more articles you might like to read next: