Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import OpenCV 4.5 in Android Studio

The fact that this question is still occasionally getting new upvotes makes me think I'm not the only one in this kind of situation, so I've decided to write a step by step explanation of what worked for me in hope that others might find it useful in the future. Everything is based on this video, but I think it's better to write a proper guide here in case it gets taken down.

If you're looking for help with OpenCV 3.4, this is what I was following before trying version 4.5.

like image 232
rdxdkr Avatar asked Jan 04 '21 22:01

rdxdkr


2 Answers

This is the complete procedure that currently works for me with OpenCV 4.5.2 on Android Studio 4.1.3.

  1. In your project click on File > New > Import Module... and select the /sdk directory inside your OpenCV download. Give it a meaningful name and wait for the procedure to finish: the directory you selected should have been copied in the root of your project where the default /app directory resides;
  2. open the Project Structure (for example by clicking on File > Project Structure...), then go to Dependencies (on the left), click on app and on the + icon in the Declared Dependencies tab (not the one in the Modules tab);
  3. click on Module Dependency and select the checkbox for the OpenCV SDK that you imported earlier. You should now see it in the list with the other dependencies, so click on Apply and OK to exit from the Project Structure;
  4. open the build.gradle file of your app module, copy the values of compileSdkVersion, minSdkVersion and targetSdkVersion, then paste them in the build.gradle file of the OpenCV module replacing the default ones so they match exactly. You can also update the sourceCompatibility and targetCompatibility fields to JavaVersion.VERSION_1_8;
  5. finally, sync your project with Gradle files.

To check if it works, add this snippet to your code, for example in MainActivity:

if (OpenCVLoader.initDebug()) {
    Log.d("myTag", "OpenCV loaded")
}
like image 196
rdxdkr Avatar answered Sep 27 '22 00:09

rdxdkr


The sdk directory for opencv version 4.5.3 is "opencv/sources/modules/java/android_sdk". After doing each steps on the https://stackoverflow.com/a/65571017/9486652, i got some errors and i solved it by commenting or deleting the 'arguments "-DANDROID_STL=@ANDROID_STL@"' line which is found inside build.gradle of the opencv module.

    externalNativeBuild {
         cmake {
//          arguments "-DANDROID_STL=@ANDROID_STL@"
            targets "opencv_jni_shared"
        }
    }
like image 37
Bereket Kassahun Avatar answered Sep 24 '22 00:09

Bereket Kassahun