How to use OpenCV Android in Android Studio

OpenCV Android SDK doesn't support Android Studio at the moment. In this blog, I will show you how to use OpenCV in your Android Studio application.

Final source code: https://github.com/quanhua92/OpenCV_Java_AndroidStudio

First, Download the latest "OpenCV for Android" at http://opencv.org/downloads.html
At the time of writing, the latest version is 3.0.0. We now have the file named OpenCV-3.0.0-android-sdk.zip
Extract the file to your favorite location. For example:
     /home/quanhua92/Quan404/OpenCV-android-sdk
Open Android Studio and select "Import project (Eclipse ADT, Gradle, etc.)
Select OpenCV-android-sdk/sdk/java folder.


Click Next


Click Finish



Wait until Gradle build finished as in the following picture.



Open your android application project. In our case, we create a new project called "OpenCV_Java_AndroidStudio".
Import opencv-java module: File > New > Import Module
In "New Module" window, select source directory to the opencv-java folder. Then, select import checkbox and replace module name with ":opencv-java"



Edit build.gradle to compile opencv-java project as follow:

dependencies {
    ...
    compile project(':opencv-java')
}




Remember to sync your gradle with the following button



At this time, you can import opencv class in your application. For example:

import org.opencv.core.CvType;
import org.opencv.core.Mat;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Mat test = new Mat(200, 200, CvType.CV_8UC1);
        Imgproc.equalizeHist(test, test);
    }
...
}

However, if you try to run the application, you will encounter " java.lang.UnsatisfiedLinkError: No implementation found" error as in the following picture.



To solve this problem, you need to copy compiled library from opencv-android-sdk and load the library in your application. The steps are:
- Go to "/home/quanhua92/Quan404/OpenCV-android-sdk/sdk/native"
- Copy "libs" folder into your "app/src/main" and rename it to "jniLibs"
- In our demo application, we only keep necessary architecture to reduce package size.



- Add the following code into your activity / service to load OpenCV library.
    static {
        // If you use opencv 2.4, System.loadLibrary("opencv_java")
        System.loadLibrary("opencv_java3");
    }


Great. Finally, we can integrate OpenCV into Android Studio project and use a basic equalizeHist function without crashes.
Hope you can do it. Please tell me in the comment sections if you have any problems.
In the next blog, I will show you how to use OpenCV C++ interfaces in Android Studio through JNI with NDK support.

Share this:

ABOUT THE AUTHOR

Hello, My name is Quan. I love blogging to share my knowledge to the world. Tell me want you want to read. I will try to blog about it. Have a nice day!

41 comments:

  1. Replies
    1. Thanks. Tell me if you have any problem :)

      Delete
  2. Thanks for your tutorial. However, I don't know why there is always an error saying "libopencv_java3.so" not found. I already followed every step above. Please help me to solve this puzzling bug!! Thanks so much.

    The Log is as follows:
    09-12 03:57:57.776 25480-25480/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.android.opencvandroid, PID: 25480
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.android.opencvandroid-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libopencv_java3.so"
    at java.lang.Runtime.loadLibrary(Runtime.java:366)
    at java.lang.System.loadLibrary(System.java:988)
    at com.android.opencvandroid.MainActivity.(MainActivity.java:16)
    at java.lang.reflect.Constructor.newInstance(Native Method)
    at java.lang.Class.newInstance(Class.java:1606)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

    ReplyDelete
    Replies
    1. Hi,
      This error is "couldn't find "libopencv_java3.so". It means that it can't find the libopencv_java3.so in the jniLibs/[your target architecture]. Did you copy it there? By the way, if you are using OpenCV 2.4. You should change the following line from : System.loadLibrary("opencv_java3");
      to System.loadLibrary("opencv_java");

      Delete
  3. Hi Quan,
    Thanks for this wonderful blog.Its a boon for beginners like me.I have followed the steps in this tutorial but still getting the unsatisfied link error.I have copied the files as told to.also i am using kikat 4 and nexus 5 api 19 kitkat 4.4.4 emulator.in my jnilibs folder i have arm-64v8a,armeabi,armeabi-v7a,mips,mips64,x86,x86_64 sub folders with the nescessaru libopencv_java3.so files..kindly help

    ReplyDelete
    Replies
    1. I am sorry to hear that you followed my steps but still can not use it. I can help you setup the project through TeamViewer. What do you think? If you want, please contact me through quanhua92@gmail.com. We will schedule a meeting to solve your problem :D.

      Delete
  4. Great post and great tutorial!

    Have you got around to doing the JNI/Native C++ tutorial?

    I'm looking to reuse a project I made in C++.

    Thanks in advance!

    ReplyDelete
  5. Quan, excellent tutorial to setup OpenCV. I have an issue when I try to sync gradle after "compile project(':opencv-java')". I get the following warning:

    Warning:Dependency MyApplication2:opencv-java:unspecified on project app resolves to an APK archive which is not supported as a compilation dependency. File: /Users/alex/AndroidStudioProjects/MyApplication2/opencv-java/build/outputs/apk/opencv-java-release-unsigned.apk

    and when i try to run it I get the following error:

    Dependency MyApplication2:opencv-java:unspecified on project app resolves to an APK archive which is not supported as a compilation dependency. File: /Users/alex/AndroidStudioProjects/MyApplication2/opencv-java/build/outputs/apk/opencv-java-release-unsigned.apk
    Error:Execution failed for task ':app:prepareDebugDependencies'.
    > Dependency Error. See console for details.

    Any ideas?

    ReplyDelete
  6. Quan, excellent tutorial to setup OpenCV. I have an issue when I try to sync gradle after "compile project(':opencv-java')". I get the following warning:

    Warning:Dependency MyApplication2:opencv-java:unspecified on project app resolves to an APK archive which is not supported as a compilation dependency. File: /Users/alex/AndroidStudioProjects/MyApplication2/opencv-java/build/outputs/apk/opencv-java-release-unsigned.apk

    and when i try to run it I get the following error:

    Dependency MyApplication2:opencv-java:unspecified on project app resolves to an APK archive which is not supported as a compilation dependency. File: /Users/alex/AndroidStudioProjects/MyApplication2/opencv-java/build/outputs/apk/opencv-java-release-unsigned.apk
    Error:Execution failed for task ':app:prepareDebugDependencies'.
    > Dependency Error. See console for details.

    Any ideas?

    ReplyDelete
    Replies
    1. I haven't seen such error before. Try to clean the project or delete the build folder in opencv-java.

      Delete
    2. Quan, I am wondering if it has to do withe fact that I built OpenCV SDK with external modules (https://github.com/Itseez/opencv_contrib/issues/399) from source instead of downloading it. But that is very weird. Let me know if you can replicate it.

      Delete
    3. Found the issue. I had to do this: http://stackoverflow.com/questions/27536491/how-to-import-android-project-as-library-and-not-compile-it-as-apk-android-stud

      Delete
    4. enter ---> compile project(':opencv-app')

      Delete
  7. Hi Quan! I have already successfully imported opencv library to Android Studio, but the problem for me now is how to create my own native source files & makefiles that are dependent on the opencv library. I have tried all kinds of methods but they all did not seem to work. Would you please provide any link to any existing up-to-date solutions that demonstrate how to run an opencv sample in android studio?

    ReplyDelete
    Replies
    1. This tutorial is about using OpenCV from scratch. There should be too much work to run an opencv sample. I suggest that you rewrite them with your own effort.

      Delete
    2. By the way, if you want to use OpenCV in JNI, here is my github repo to show the process. I haven't written it on my blog. https://github.com/quanhua92/NDK_OpenCV_AndroidStudio

      Delete
    3. It's a late reply but I've actually already solved my problem :). Thank you very much anyway!!!

      Delete
  8. Thank you :'( You saved my 3 weeks finding a solution :'(

    ReplyDelete
    Replies
    1. You're welcome :) Just ask here if you have any problem.

      Delete
  9. Hello, thanks for the great guide. How would I get it to not include the jniLib stuff in the APK, and instead use the OpenCV Manager? If I don't have a jniLibs folder, but use initAsync(), will it install and use the OpenCV manager for its native libs?

    ReplyDelete
    Replies
    1. Hi, if you follow the above tutorial, you don't need to use OpenCV Manager :). I don't use initAsync() function. I load the library directly from jniLibs.

      Delete
    2. I'd actually prefer to use the manager if it works, keeps my apk smaller, auto installs without issues, and stays up to date. I just have no experience with it, and would like to know your thoughts on it.

      Delete
    3. The manager gives you many advantages. It helps the library up to date and reduce the apk size. However, it may make the user confused. When they open your app for the first time, a popup will appear and they must move to the google play store. If the user doesn't want to install opencv manager ( because they don't know what it is ), you will lose the chance to impress the user at the first time. I prefer including the library in my apk. If you understand the JNI make files, you can reduce still the size of the library by removing unnecessary libraries.

      Delete
    4. Alright, thanks for the info. I see what you mean by the drawbacks of confusing user. If you were distributing over the play store to lots of different types of devices, wouldn't you have to include a lot native code for the different architectures? I was including a bunch of native libs in my apk. When I removed my jniLib folder and depended on the manager my apk went from 37 megs to 1.2 megs, but maybe that's an extreme case. If you were writing some custom native code I guess you'll always have to include some stuff in jniLibs, but I haven't ventured down that path yet.

      Delete
  10. Hi, you did great job, but my question is about using nonfree modules. I need to work with algorithms for key point detection which are not included in newest version for android. It is avaliable in special repository on github(not included in basic version of opencv3.0.0 even for windows). Do you know how to put it in your project?

    ReplyDelete
    Replies
    1. Thank. I haven't tried to compile nonfree modules. Did you success?

      Delete
  11. I had an issue with the initial Gradle compile during import.
    Error:Cause: failed to find target with hash string 'android-14' in:
    All I had to do was edit the app build.gradle to:
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    Originally it was:
    compileSdkVersion 14
    buildToolsVersion "23.0.2"

    ReplyDelete
    Replies
    1. The problem is that you don't have android sdk version 14. You can download additional sdk in "Tools>Android>SDK Manager"

      Delete
  12. Hey! Great tutorial :)
    I followed this tutorial and I could compile this project...now, Can I compile the examples of Opencv?...Do you have a tutorial about this?

    ReplyDelete
    Replies
    1. Hi, I haven't tried to compile examples. I may try to make a tutorial later. However, I think you can try to understand the example and copy the code to a working project in Android Studio.

      Delete
  13. Hello great Tutorial Thanks so much! I am so close, i just don't know what to put at System.loadLibrary("opencv_java"); since i am using openCV 3.1 any tips?

    I know it is working since when i add the imports and run there is no error, only when i add the code on the last step. Thanks a ton for your time and help!

    ReplyDelete
    Replies
    1. Hi, you can try System.loadLibrary("opencv_java3");. You may want to look at jniLibs folder in your project. For example: https://github.com/quanhua92/OpenCV_Java_AndroidStudio/tree/master/app/src/main/jniLibs/armeabi-v7a, you will see "libopencv_java3.so". This means you need to load "opencv_java3" (Remove 'lib' and '.so' part).

      Delete
    2. Very cool thanks for the quick reply!!! I tried the System.loadLibrary("opencv_java3"); , i will look over again to make sure i didnt miss something. If I seem to have trouble will you have sometime to try a team viewer session sometime?

      Thanks so much for your time and help.

      Delete
    3. It worked! Complied and ran with no errors. Thanks a ton!

      Delete
    4. Do you have any experience in getting an openCV example working in Android Studio? I want to run the face detection example, and i figured importing the module after following your tutorial should allow that but it is not working.

      This would help me a lot, thanks for your time and help!
      Have a great day!

      Delete
  14. Thank you it works like charm. But how can i reduce apk file size?

    ReplyDelete
    Replies
    1. Hi,
      Thank you for your interested in my post. You can remove some opencv .so files which belongs to library parts that you won't ever use.

      Delete
  15. Hi Quan! It is such a well written article! I really enjoyed reading it. Lately, I was building an app and I needed to integrate Android Studio project with OpenCV and I’ve found this: http://blog.zaven.co/opencv-in-android-studio-project/ It really helped me. Maybe it will be as helpful for other users as it was for me.

    ReplyDelete
  16. wonderful Tutorial :) I am working on object tracking through colors. I am working through Galaxy Note 5, which have a good processing capability I guess. The problem is that the application is not running fast. I would like to know whether this issue is related to native calls "Since I'm new to opencv with android", I don't know whether I am making a native call or not. On the other hand, I may be related to the processor. Could you please help me out with this problem :) Thank u

    ReplyDelete
    Replies
    1. Hi, I think that you should lower the number of frames per second. Basically, you don't need 30 fps to perform a good object tracking.

      Delete
  17. This is an important concern when, with every quarter, competition growing like never before. Be it iPhone app development or any app development for iPad, Android is always under tough competition.
    showboxdownloadsapp.com

    ReplyDelete