Tuesday, February 7, 2017

How to Load Java OpenCV Library to Android Studio

In this tutorial, I will go through a step by step method to load Java OpenCV Library to Android Studio.

First, download OpenCV for Android from here. Extract the zip file, and you should see OpenCV-android-sdk folder.

Next, in Android Studio, open up a project where you want to integrate OpenCV Java library. Then, click File - New - Import Module and select OpenCV-android-sdk/sdk/java folder. Android Studio will ask about import option, and just accept the default.

You should see OpenCVLibrary module in your Android project. Select its build.gradle file and set appropriate versions for compileSdkVersion, buildToolsVersion, etc.

Now, you need to add dependency. Open up your app's build.gradle file and add
compile project(':openCVLibrary310')
into dependencies { ... } section.

Next, you will need to make sure that your app loads in the OpenCV library. Go to the activity class file that first uses OpenCV Library, and add static statement, similar to below:

...
import org.opencv.android.OpenCVLoader;

public class MainActivity extends Activity {
    final static String TAG = "Main Activity";

    static {
        if(!OpenCVLoader.initDebug()){
            Log.d(TAG, "OpenCV not loaded");
        } else {
            Log.d(TAG, "OpenCV loaded");
        }
    }
...

Finally, you will need to copy native binary files. Copy OpenCV-android-sdk/sdk/native/libs folder as src/main/jniLibs folder in your app's directory.

That's it! You should now be able to use OpenCV functions in your app!

No comments:

Post a Comment