Skip to content

Instantly share code, notes, and snippets.

@Tanapruk
Last active August 20, 2018 13:52
Show Gist options
  • Save Tanapruk/25e1d73e7c2b481d28898eb3d5f00294 to your computer and use it in GitHub Desktop.
Save Tanapruk/25e1d73e7c2b481d28898eb3d5f00294 to your computer and use it in GitHub Desktop.
Attach openCV sdk to your Android Studio project.

###There is no official maven-based way to install OpenCV on Android. You have to download and set it up to your project.

  1. Download the sdk and extract it somewhere.

  2. File>New>Import Module and select sdk/java

└── sdk
    ├── etc
    ├── java
    └── native
  1. Go to openCVLibrary320/build.gradle, change compileSDKVersion to 25 and resync
  2. Right Click at openCVLibrary320 New>Folder>JNI Folder
  3. Change Folder Location and type src/main/jniLibs/
  4. Go to sdk/native/libs and copy all folders inside libs
native
├── 3rdparty
├── jni
└── libs
    ├── arm64-v8a
    ├── armeabi
    ├── armeabi-v7a
    ├── mips
    ├── mips64
    ├── x86
    └── x86_64
  1. Paste them in the jniLibs folder
  2. Remove all .a files since we only need .so files only in Android. You can manully delete it or use this command find . -name "*.a" -type f -delete.
  3. Remove sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jniLibs/'] } } from openCV320Library/build.gradle I don't know why but including this won't make the app compile. Removing it results in a compilation successs.
  4. Add compile project(path: ':openCVLibrary320') in your build.gradle of your main module.
  5. Test if OpenCV is loaded correctly by adding static ...
public class MainActivity extends AppCompatActivity {
 
    private static final String TAG = "MainActivity";
 
    static {
        if(!OpenCVLoader.initDebug()){
            Log.d(TAG, "OpenCV not loaded");
        } else {
            Log.d(TAG, "OpenCV loaded");
        }
    }
  ....

C++

Incase you have .cpp files. You have to put them in jni folder. Also, You are required to put either Android.mk or CMakeLists.txt in your jni folder. In your gradle build, add below inside android closure.

  externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment