72

I want to use Android Studio to develop an app using Gradle build tool. I can not insert the OpenCV repo and library on build.gradle. My .gradle file is like below:

buildscript {
    repositories {
        mavenCentral()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

How can I add OpenCV in my project?

moken
  • 3,227
  • 8
  • 13
  • 23
Omer Sonmez
  • 1,168
  • 2
  • 20
  • 31

12 Answers12

138

You can do this very easily in Android Studio.

Follow the below steps to add Open CV in your project as library.

  1. Create a libraries folder underneath your project main directory. For example, if your project is OpenCVExamples, you would create a OpenCVExamples/libraries folder.

  2. Go to the location where you have SDK "\OpenCV-2.4.8-android-sdk\sdk" here you will find the java folder, rename it to opencv.

  3. Now copy the complete opencv directory from the SDK into the libraries folder you just created.

  4. Now create a build.gradle file in the opencv directory with the following contents

    apply plugin: 'android-library'
    
    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.9.+'
        }
    }
    
    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.1"
    
        defaultConfig {
            minSdkVersion 8
            targetSdkVersion 19
            versionCode 2480
            versionName "2.4.8"
        }
    
        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                resources.srcDirs = ['src']
                res.srcDirs = ['res']
                aidl.srcDirs = ['src']
            }
        }
    }
    
  5. Edit your settings.gradle file in your application’s main directory and add this line:

    include ':libraries:opencv'
    
  6. Sync your project with Gradle and it should looks like this

    screen 1

  7. Right click on your project then click on the Open Module Settings then Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new module dependency.

    enter image description here

  8. Choose Module dependency. It will open a dialog with a list of modules to choose from; select “:libraries:opencv”.

    enter image description here

  9. Create a jniLibs folder in the /app/src/main/ location and copy the all the folder with *.so files (armeabi, armeabi-v7a, mips, x86) in the jniLibs from the OpenCV SDK.

    enter image description here

  10. Click OK. Now everything done, go and enjoy with OpenCV.

Ajay S
  • 48,003
  • 27
  • 91
  • 111
  • 22
    "You can do this very easily in Android Studio." - Yeah, right, completely straightforward... :) But huge thanks, your solution finally helped me to get this to build. I want to ask about copying the files into the jniLibs directory. It copied like 150 megabytes of data. Will these all be included in the final application and if yes, are they necessary? I mean is it possible to include the opencv without making the application unnecessarily large? – Laky Mar 25 '14 at 14:34
  • Ok, so the app in my phone has roughly "only" 40 MB in the end, but I have a problem, I get this error: `UnsatisfiedLinkError: Native method not found: org.opencv.features2d.FeatureDetector.create_0:(I)J`. Do you know what can be the reason? – Laky Mar 25 '14 at 15:47
  • Hi.. I was not able to find the Java folder under OpenCV sdk i downloaded from OpenCV website. Can you please help me through this – Vinuthan Aug 11 '14 at 09:25
  • 1
    @Vinuthan: be sure that you downloaded the OpenCV Android SDK and not just OpenCV. You want the `OpenCV for Android` link [here](http://opencv.org/downloads.html). It sounds like you may have grabbed the wrong one. As of OpenCV Android 2.4.9 I was able to find the folder in `sdk/java/`. – user1978019 Aug 15 '14 at 22:44
  • If you get the UnsatisfiedLinkError: No implementation found for.... error, make sure you add your code in these brackets: `if(OpenCVLoader.initDebug()){ //your openCV code here }` – AggieDev Dec 02 '14 at 20:37
  • Can confirm, this also works with 2.4.10 and android studio 1.0. – Utkarsh Sinha Dec 25 '14 at 10:04
  • Your solution is awesome. But I faced some problem with dependencies { classpath 'com.android.tools.build:gradle:1.0.+' } I can only use 1.0.+ and it ask me to upgrade the buildToolsVersion "19.1.0" now, all have been solved. – Albert Chen Jan 08 '15 at 19:25
  • It seems to me the main/ should go in the project root, not in src/. This is documented by Google: https://developer.android.com/tools/projects/index.html Putting it in src/ causes the .so libraries to be duplicated in the .apk – jacob Feb 27 '15 at 03:33
  • Thanks. It Works :) +1 – Jamil Sep 12 '15 at 20:01
  • Thanks for the step-by-step guide. However, I am still encountering the UnsatisfiedLinkError: No implementation found for.... error. I also used if(OpenCVLoader.initDebug()){ //your openCV code here }, however, it turned out that initDebug() fails. Any ideas what I am doing wrong? – Heribert Nov 11 '15 at 15:45
  • 5
    In step 9, I don't see a `jniLibs` folder in the OpenCV SDK. After some looking, I did find the folders with the *.so files, but they were in this directory: `OpenCV-3.0.0-android-sdk-1\OpenCV-android-sdk\sdk\native\libs` Could it just be that I'm using a newer version of the OpenCV SDK? – Greg Nov 28 '15 at 14:08
  • Worked like a charm!! – The Hungry Androider Mar 20 '16 at 04:50
  • @Laky I too was getting an .apk with ~40mb... What I did was to delete every folder inside the `jniLibs/` except `armeabi-v7a/`. Now my signed release .apk is 5.7 MB. But removing those folders means that not every device is supported right? I wonder if there is any other way... – Henrique Ferrolho Jun 03 '16 at 01:28
  • Build tools 19.0.1 are no longer available; should update to 19.1 – moof2k Sep 03 '16 at 23:17
  • You will need to update the buildgradle in opencv to the following android { compileSdkVersion 24 buildToolsVersion "24.0.0" defaultConfig { minSdkVersion 19 targetSdkVersion 24 Maybe even to 21, as I see there is references to camera2 which is api 21 – StarWind0 Nov 13 '16 at 06:38
  • 2
    @TGMCians In step 6 I got this error: _**Error:Cannot read packageName from project-path/libraries/AndroidManifest.xml**_. Is it should make a modification? And how? – frank jorsn Apr 14 '17 at 03:48
  • The OpenCV Android SDK has added support for gradle. See my answer here: https://stackoverflow.com/a/49126531/755405 – W1M0R Mar 06 '18 at 08:58
  • I got the same issue of can't read packageName from the project. I placed the file in wrong places. So, Please place the build.gradle file in opencv folder rather than libraries. – Rakesh Apr 02 '18 at 11:37
  • getting `ERROR: module not specified` on running `opencv` module in android studio and also getting `false` to `OpenCVLoader.initDebug()` on running `app` module? I followed exact steps and searched online but no solution found. – androidGeek Nov 23 '19 at 16:29
  • Ajay or can someone help me in this matter, I really need to do this. https://stackoverflow.com/questions/61876457/image-segmentation-using-segment-seeds-watershed-in-android – Tecnologia da Net May 18 '20 at 19:40
36

Since the integration of OpenCV is such an effort, we pre-packaged it and published it via JCenter here: https://github.com/quickbirdstudios/opencv-android

Just include this in your module's build.gradle dependencies section

dependencies {
  implementation 'com.quickbirdstudios:opencv:3.4.1'
}

and this in your project's build.gradle repositories section

repositories {
  jcenter()
}

You won't get lint error after gradle import but don't forget to initialize the OpenCV library like this in MainActivity

public class MainActivity extends Activity {
    static {
        if (!OpenCVLoader.initDebug())
            Log.d("ERROR", "Unable to load OpenCV");
        else
            Log.d("SUCCESS", "OpenCV loaded");
    }
...
...
...
...
HimalayanCoder
  • 9,630
  • 6
  • 59
  • 60
Malte
  • 561
  • 5
  • 7
25

As per OpenCV docs(1), below steps using OpenCV manager is the recommended way to use OpenCV for production runs. But, OpenCV manager(2) is an additional install from Google play store. So, if you prefer a self contained apk(not using OpenCV manager) or is currently in development/testing phase, I suggest answer at https://stackoverflow.com/a/27421494/1180117.

Recommended steps for using OpenCV in Android Studio with OpenCV manager.

  1. Unzip OpenCV Android sdk downloaded from OpenCV.org(3)
  2. From File -> Import Module, choose sdk/java folder in the unzipped opencv archive.
  3. Update build.gradle under imported OpenCV module to update 4 fields to match your project's build.gradle a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and 4) targetSdkVersion.
  4. Add module dependency by Application -> Module Settings, and select the Dependencies tab. Click + icon at bottom(or right), choose Module Dependency and select the imported OpenCV module.

As the final step, in your Activity class, add snippet below.

    public class SampleJava extends Activity  {

        private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch(status) {
                case LoaderCallbackInterface.SUCCESS:
                    Log.i(TAG,"OpenCV Manager Connected");
                    //from now onwards, you can use OpenCV API
                    Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
                    break;
                case LoaderCallbackInterface.INIT_FAILED:
                    Log.i(TAG,"Init Failed");
                    break;
                case LoaderCallbackInterface.INSTALL_CANCELED:
                    Log.i(TAG,"Install Cancelled");
                    break;
                case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION:
                    Log.i(TAG,"Incompatible Version");
                    break;
                case LoaderCallbackInterface.MARKET_ERROR:
                    Log.i(TAG,"Market Error");
                    break;
                default:
                    Log.i(TAG,"OpenCV Manager Install");
                    super.onManagerConnected(status);
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        //initialize OpenCV manager
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, mLoaderCallback);
    }
}

Note: You could only make OpenCV calls after you receive success callback on onManagerConnected method. During run, you will be prompted for installation of OpenCV manager from play store, if it is not already installed. During development, if you don't have access to play store or is on emualtor, use appropriate OpenCV manager apk present in apk folder under downloaded OpenCV sdk archive .

Pros

  • Apk size reduction by around 40 MB ( consider upgrades too ).
  • OpenCV manager installs optimized binaries for your hardware which could help speed.
  • Upgrades to OpenCV manager might save your app from bugs in OpenCV.
  • Different apps could share same OpenCV library.

Cons

  • End user experience - might not like a install prompt from with your application.
Community
  • 1
  • 1
kiranpradeep
  • 10,859
  • 4
  • 50
  • 82
  • How can I use it with NDK and JNI using C++? – Romantic Electron Apr 14 '15 at 18:11
  • @RomanticElectron I haven't tried opencv with ndk. I would like to know for which particular functionality of opencv you use ndk. With 3.0 , Java wrappers for opencv have really improved. – kiranpradeep Apr 15 '15 at 03:59
  • I want to use Stroke Width Transform algorithm for text detection , get Connected Components and separate out letters for giving input to a Neural Network @Kiran – Romantic Electron Apr 15 '15 at 05:22
  • I have no idea what the include static{ System.loadLibrary("opencv_java"); } thing does (or where to put it), but this is the correct answer to this question. Thanks! Also there is another bug fix you need too. See: http://stackoverflow.com/questions/27470313/opencv-service-intent-must-be-explicit-android-5-0-lolipop – Dave Fisher Apr 30 '15 at 03:31
  • Sorry but where do you put the static call? – Razgriz May 02 '15 at 09:44
  • Most important: do not forget to specify permissions and features in AndroidManifest.xml file – Swadesh Jul 22 '15 at 03:17
  • My problem is that calling OpenCV methods from onManagerConnected causes UnsatisfiedLinkError in certain cases. Imgproc.blur is working and I can save and see the blurred image but Imgproc.Canny is not working: "No implementation found for void org.opencv.imgproc.Imgproc.Canny_3". If I copy OpenCV's libs to projects' jniLibs then everything works fine including Canny. Although large apk size is worrying what bothers me more is the ridiculous +1GB build directory eating up my Dropbox space for a tiny app. I tried Android 4.2.2 and 6.0 with the latest OpenCV 3.2.0. What could be the problem? – rics Feb 10 '17 at 19:32
  • @rics: It turned out that I used the OpenCV Manager from Google Play and unfortunately it still contains OpenCV 3.0 instead of OpenCV 3.2.0. The OpenCV Manager apk for 3.2.0 can be found in OpenCV for Android SDK download. With that program Canny works fine and the program and the build size are much smaller. – rics Feb 14 '17 at 08:57
9

If you don't want to use JavaCV this works for me...

Step 1- Download the Resources

Download OpenCV Android SDK from http://opencv.org/downloads.html

Step 2 - Copying the OpenCV binaries into your APK

Copy libopencv_info.so & libopencv_java.so from

OpenCV-2.?.?-android-sdk -> sdk -> native -> libs -> armeabi-v7a

to

Project Root -> Your Project -> lib - > armeabi-v7a

Zip the lib folder up and rename that zip to whatever-v7a.jar.

Copy this .jar file and place it in here in your project

Project Root -> Your Project -> libs

Add this line to your projects build.gradle in the dependencies section

compile files('libs/whatever-v7a.jar')

When you compile now you will probably see your .apk is about 4mb bigger.

(Repeat for "armeabi" if you want to support ARMv6 too, likely not needed anymore.)

Step 3 - Adding the java sdk to your project

Copy the java folder from here

OpenCV-2.?.?-android-sdk -> sdk

to

Project Root -> Your Project -> libs (Same place as your .jar file);

(You can rename the 'java' folder name to 'OpenCV')

In this freshly copied folder add a typical build.gradle file; I used this:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
    }
}

apply plugin: 'android-library'

repositories {
    mavenCentral();
}

android {
    compileSdkVersion 19
    buildToolsVersion "19"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 19
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}

In your Project Root settings.gradle file change it too look something like this:

include ':Project Name:libs:OpenCV', ':Project Name'

In your Project Root -> Project Name -> build.gradle file in the dependencies section add this line:

compile project(':Project Name:libs:OpenCV')

Step 4 - Using OpenCV in your project

Rebuild and you should be able to import and start using OpenCV in your project.

import org.opencv.android.OpenCVLoader;
...
if (!OpenCVLoader.initDebug()) {}

I know this if a bit of hack but I figured I would post it anyway.

Paito
  • 1,553
  • 1
  • 15
  • 24
  • This worked up to a point, but I can't import the OpenCV classes into my project. I can import `org.opencv` - which is recognized, but if I try to import e.g. `org.opencv.android.OpenCVLoader`, `android` is underlined in red, as are any other classes I try and import. What might be going wrong? – fredley Jan 13 '14 at 10:42
  • Are you sure you downloaded "OpenCV for Android" from OpenCV.org in Step #1? If so, it sounds like something went wrong in Step #3. Hope that helps.. – Paito Jan 13 '14 at 14:19
  • I did, yes, I think the problem was not rebuilding, it's fixed now. – fredley Jan 13 '14 at 15:16
  • Good to hear Tom! BTW - As of Android Studio 0.4.2 I think they have some NDK support, I would like to check that out soon, it might result in smaller APK sizes. – Paito Jan 13 '14 at 18:59
  • I followed your steps and I'm getting: Couldn't load opencv_java: findLibrary returned null. I followed them from scratch twice with same result. Using Android Studio 0.5.1. I can call initDebug from main, but seems like the underlying libs are not found? Any thoughts? Thank you! – albertpeiro Mar 19 '14 at 13:41
  • I am not familiar with initDebug, I am guessing it's because the OpenCV source isn't attached. Can you try ```gradlew assembleDebug```? I works for me with Android Studio 0.5.1. – Paito Mar 19 '14 at 13:54
  • Build is successful. It builds and runs the app in both emulator and device, though when the code in Step 4) if (!OpenCVLoader.initDebug()) {} is executed it throws a silent exception saying: Couldn't load opencv_java: findLibrary returned null. Also your suggested gradlew command says everything is either not marked or UP-TO-DATE and conclusion BUILD SUCCESSFUL – albertpeiro Mar 19 '14 at 15:43
  • Oops I thought you were running ```gradlew initDebug```, now I see it was just the OpenCGVLoader, duh! Ok, I am guessing it's an issue with the way the .so's are packaged in your .apk. Maybe post a new question on SO with a picture? I can try and help more from there. – Paito Mar 19 '14 at 15:55
  • @Paito My issues following the steps: http://stackoverflow.com/questions/22516291/how-to-package-and-link-opencv-binares-and-opencv-java-sdk-for-android-studio Many thanks! – albertpeiro Mar 19 '14 at 19:35
8

I have posted a new post about how to build an Android NDK application with OpenCV included using Android Studio and Gradle. More information can be seen here, I have summarized two methods:

(1) run ndk-build within Gradle task

sourceSets.main.jni.srcDirs = []

task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
    ndkDir = project.plugins.findPlugin('com.android.application').getNdkFolder()
    commandLine "$ndkDir/ndk-build",
            'NDK_PROJECT_PATH=build/intermediates/ndk',
            'NDK_LIBS_OUT=src/main/jniLibs',
            'APP_BUILD_SCRIPT=src/main/jni/Android.mk',
            'NDK_APPLICATION_MK=src/main/jni/Application.mk'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}

(2) run ndk-build with an external tool

Parameters: NDK_PROJECT_PATH=$ModuleFileDir$/build/intermediates/ndk NDK_LIBS_OUT=$ModuleFileDir$/src/main/jniLibs NDK_APPLICATION_MK=$ModuleFileDir$/src/main/jni/Application.mk APP_BUILD_SCRIPT=$ModuleFileDir$/src/main/jni/Android.mk V=1

More information can be seen here

javayhu
  • 141
  • 2
  • 8
7
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
    maven {
        url 'http://maven2.javacv.googlecode.com/git/'
    }
}

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
    compile 'com.googlecode.javacv:javacv:0.5'
    instrumentTestCompile 'junit:junit:4.4'
}

android {
    compileSdkVersion 14
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 14
    }
}

This is worked for me :)

Omer Sonmez
  • 1,168
  • 2
  • 20
  • 31
  • 2
    this is for javacv (opencv wrapper) and now it has been changed to "org.bytedeco:javacv:" – Avinash R Aug 04 '14 at 11:16
  • after adding the items above, I got a 'java.lang.UnsatisfiedLinkError: Couldn't load opencv_core from loader dalvik.system.PathClassLoader' exception. Any idea that what's missing? (For the record I added 'complie org.bytedeco.javacv:0.9+') – Hegi Sep 19 '14 at 20:52
  • @Hegi those links may help. http://stackoverflow.com/questions/22516291/how-to-package-and-link-opencv-binares-and-opencv-java-sdk-for-android-studio http://stackoverflow.com/questions/21998366/unsatified-link-error-android-opencv – Omer Sonmez Sep 20 '14 at 22:36
5

It works with Android Studio 1.2 + OpenCV-2.4.11-android-sdk (.zip), too.

Just do the following:

1) Follow the answer that starts with "You can do this very easily in Android Studio. Follow the steps below to add OpenCV in your project as library." by TGMCians.

2) Modify in the <yourAppDir>\libraries\opencv folder your newly created build.gradle to (step 4 in TGMCians' answer, adapted to OpenCV2.4.11-android-sdk and using gradle 1.1.0):

apply plugin: 'android-library'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
    }
}

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 21
        versionCode 2411
        versionName "2.4.11"
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            aidl.srcDirs = ['src']
        }
    }
}

3) *.so files that are located in the directories "armeabi", "armeabi-v7a", "mips", "x86" can be found under (default OpenCV-location): ..\OpenCV-2.4.11-android-sdk\OpenCV-android-sdk\sdk\native\libs (step 9 in TGMCians' answer).

Enjoy and if this helped, please give a positive reputation. I need 50 to answer directly to answers (19 left) :)

Rob
  • 101
  • 1
  • 5
4

The OpenCV Android SDK has an example gradle.build file with helpful comments: https://github.com/opencv/opencv/blob/master/modules/java/android_sdk/build.gradle.in

//
// Notes about integration OpenCV into existed Android Studio application project are below (application 'app' module should exist).
//
// This file is located in <OpenCV-android-sdk>/sdk directory (near 'etc', 'java', 'native' subdirectories)
//
// Add module into Android Studio application project:
//
// - Android Studio way:
//   (will copy almost all OpenCV Android SDK into your project, ~200Mb)
//
//   Import module: Menu -> "File" -> "New" -> "Module" -> "Import Gradle project":
//   Source directory: select this "sdk" directory
//   Module name: ":opencv"
//
// - or attach library module from OpenCV Android SDK
//   (without copying into application project directory, allow to share the same module between projects)
//
//   Edit "settings.gradle" and add these lines:
//
//   def opencvsdk='<path_to_opencv_android_sdk_rootdir>'
//   // You can put declaration above into gradle.properties file instead (including file in HOME directory),
//   // but without 'def' and apostrophe symbols ('): opencvsdk=<path_to_opencv_android_sdk_rootdir>
//   include ':opencv'
//   project(':opencv').projectDir = new File(opencvsdk + '/sdk')
//
//
//
// Add dependency into application module:
//
// - Android Studio way:
//   "Open Module Settings" (F4) -> "Dependencies" tab
//
// - or add "project(':opencv')" dependency into app/build.gradle:
//
//   dependencies {
//       implementation fileTree(dir: 'libs', include: ['*.jar'])
//       ...
//       implementation project(':opencv')
//   }
//
//
//
// Load OpenCV native library before using:
//
// - avoid using of "OpenCVLoader.initAsync()" approach - it is deprecated
//   It may load library with different version (from OpenCV Android Manager, which is installed separatelly on device)
//
// - use "System.loadLibrary("opencv_java3")" or "OpenCVLoader.initDebug()"
//   TODO: Add accurate API to load OpenCV native library
//
//
//
// Native C++ support (necessary to use OpenCV in native code of application only):
//
// - Use find_package() in app/CMakeLists.txt:
//
//   find_package(OpenCV 3.4 REQUIRED java)
//   ...
//   target_link_libraries(native-lib ${OpenCV_LIBRARIES})
//
// - Add "OpenCV_DIR" and enable C++ exceptions/RTTI support via app/build.gradle
//   Documentation about CMake options: https://developer.android.com/ndk/guides/cmake.html
//
//   defaultConfig {
//       ...
//       externalNativeBuild {
//           cmake {
//               cppFlags "-std=c++11 -frtti -fexceptions"
//               arguments "-DOpenCV_DIR=" + opencvsdk + "/sdk/native/jni" // , "-DANDROID_ARM_NEON=TRUE"
//           }
//       }
//   }
//
// - (optional) Limit/filter ABIs to build ('android' scope of 'app/build.gradle'):
//   Useful information: https://developer.android.com/studio/build/gradle-tips.html (Configure separate APKs per ABI)
//
//   splits {
//       abi {
//           enable true
//           reset()
//           include 'armeabi-v7a' // , 'x86', 'x86_64', 'arm64-v8a'
//           universalApk false
//       }
//   }
//

apply plugin: 'com.android.library'

println "OpenCV: " + project.buildscript.sourceFile

android {
    compileSdkVersion 27
    //buildToolsVersion "27.0.3" // not needed since com.android.tools.build:gradle:3.0.0

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 21
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }

    sourceSets {
        main {
            jniLibs.srcDirs = ['native/libs']
            java.srcDirs = ['java/src']
            aidl.srcDirs = ['java/src']
            res.srcDirs = ['java/res']
            manifest.srcFile 'java/AndroidManifest.xml'
        }
    }
}

dependencies {
}
W1M0R
  • 3,367
  • 3
  • 30
  • 32
3

These are the steps necessary to use OpenCV with Android Studio 1.2:

  • Download OpenCV and extract the archive
  • Open your app project in Android Studio
  • Go to File -> New -> Import Module...
  • Select sdk/java in the directory you extracted before
  • Set Module name to opencv
  • Press Next then Finish
  • Open build.gradle under imported OpenCV module and update compileSdkVersion and buildToolsVersion to versions you have on your machine
  • Add compile project(':opencv') to your app build.gradle

    dependencies {
        ...
        compile project(':opencv')
    }
    
  • Press Sync Project with Gradle Files

Mattia Maestrini
  • 32,270
  • 15
  • 87
  • 94
2

I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android

You can include it on your project only adding two lines into build.gradle file thanks to jitpack.io service.

allgood
  • 529
  • 5
  • 11
1

The following permissions and features are necessary in the AndroidManifest.xml file without which you will get the following dialog box

"It seems that your device does not support camera (or it is locked). Application will be closed"

  <uses-permission android:name="android.permission.CAMERA"/>

    <uses-feature android:name="android.hardware.camera" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>
Swadesh
  • 651
  • 2
  • 8
  • 22
1

OpenCV, Android Studio 1.4.1, gradle-experimental plugin 0.2.1

None of the other answers helped me. Here's what worked for me. I'm using the tutorial-1 sample from opencv but I will be doing using the NDK in my project so I'm using the gradle-experimental plugin which has a different structure than the gradle plugin.

Android studio should be installed, the Android NDK should be installed via the Android SDK Manager, and the OpenCV Android SDK should be downloaded and unzipped.

This is in chunks of bash script to keep it compact but complete. It's also all on the command line because on of the big problems I had was that in-IDE instructions were obsolete as the IDE evolved.

First set the location of the root directory of the OpenCV SDK.

export OPENCV_SDK=/home/user/wip/OpenCV-2.4.11-android-sdk
cd $OPENCV_SDK

Create your gradle build files...

First the OpenCV library

cat > $OPENCV_SDK/sdk/java/build.gradle <<'==='


apply plugin: 'com.android.model.library'
model {
    android {
        compileSdkVersion = 23
        buildToolsVersion = "23.0.2"

        defaultConfig.with {
            minSdkVersion.apiLevel = 8
            targetSdkVersion.apiLevel = 23
        }
    }

    android.buildTypes {
        release {
            minifyEnabled = false
        }
        debug{
            minifyEnabled = false
        }
    }
   android.sources {
       main.manifest.source.srcDirs +=  "."
       main.res.source.srcDirs +=  "res"
       main.aidl.source.srcDirs +=  "src"
       main.java.source.srcDirs +=  "src"
   }

}


===

Then tell the tutorial sample what to label the library as and where to find it.

cat > $OPENCV_SDK/samples/tutorial-1-camerapreview/settings.gradle <<'==='


include ':openCVLibrary2411'
project(':openCVLibrary2411').projectDir = new File('../../sdk/java')


===

Create the build file for the tutorial.

cat > $OPENCV_SDK/samples/tutorial-1-camerapreview/build.gradle <<'==='


buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle-experimental:0.2.1'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

apply plugin: 'com.android.model.application'

model {
    android {
        compileSdkVersion = 23
        buildToolsVersion = "23.0.2"

        defaultConfig.with {
            applicationId = "org.opencv.samples.tutorial1"
            minSdkVersion.apiLevel = 8
            targetSdkVersion.apiLevel = 23
        }
    }

    android.sources {
       main.manifest.source.srcDirs +=  "."
       main.res.source.srcDirs +=  "res"
       main.aidl.source.srcDirs +=  "src"
       main.java.source.srcDirs +=  "src"
    } 

    android.buildTypes {
        release {
            minifyEnabled = false
            proguardFiles += file('proguard-rules.pro')
        }
        debug {
             minifyEnabled = false
        }
    }
}

dependencies {
    compile project(':openCVLibrary2411')
}


===

Your build tools version needs to be set correctly. Here's an easy way to see what you have installed. (You can install other versions via the Android SDK Manager). Change buildToolsVersion if you don't have 23.0.2.

echo "Your buildToolsVersion is one of: "
ls $ANDROID_HOME/build-tools

Change the environment variable on the first line to your version number

REP=23.0.2 #CHANGE ME
sed -i.bak s/23\.0\.2/${REP}/g $OPENCV_SDK/sdk/java/build.gradle
sed -i.bak s/23\.0\.2/${REP}/g $OPENCV_SDK/samples/tutorial-1-camerapreview/build.gradle

Finally, set up the correct gradle wrapper. Gradle needs a clean directory to do this.

pushd $(mktemp -d)

gradle wrapper --gradle-version 2.5

mv -f gradle* $OPENCV_SDK/samples/tutorial-1-camerapreview
popd

You should now be all set. You can now browse to this directory with Android Studio and open up the project.

Build the tutoral on the command line with the following command:

./gradlew assembleDebug

It should build your apk, putting it in ./build/outputs/apk

hauptmech
  • 353
  • 2
  • 11