I want to use OpenCV library in my app with Android Studio. I followed instructions found here but I get error
Configuration with name 'default' not found
What can be wrong?
I use Android Studio 1.0 with gradle 2.2.1.
I want to use OpenCV library in my app with Android Studio. I followed instructions found here but I get error
Configuration with name 'default' not found
What can be wrong?
I use Android Studio 1.0 with gradle 2.2.1.
The below steps for using Android OpenCV sdk in Android Studio. This is a simplified version of this SO answer.
Step (6) is since Android studio expects native libs in app/src/main/jniLibs
instead of older libs
folder. For those new to Android OpenCV, don't miss below steps
static{ System.loadLibrary("opencv_java"); }
(Note: for OpenCV version 3 at this step you should instead load the library opencv_java3
.)OpenCV written is in C/C++. Java wrappers are
javadocs
directory ?.It's also asking me for installing android sdk 14
though I am targetting devices that support android sdk 15
–
Nardone OpenCV4Android 2.4.9
, I have completed step 4 but I am unable to find the sdk/native
directory in my sdk
directory.Am I missing something? –
Nardone native
folder is present. Not sure why it is missing for you. –
Turmeric sdk
installation directory on my system while you were talking about the directory which comes with Android Open CV SDK
.Ok completed step 6. Where do I include static{ System.loadLibrary("opencv_java"); }
? –
Nardone android-14
error after importing the module in step 2, you need to manually edit the build.gradle
in the openCV directory in your project as shown in step 3. –
Thermostatics System.loadLibrary("opencv_java3")
while the .so file is named libopencv_java3? –
Alkmaar externalNativeBuild
or ndk
block is not found in build.gradle
file. Recent updates in Android Studio 2.3.0 has received that kind of integration. Please check my answer for more information: https://mcmap.net/q/145478/-adding-opencv-to-native-c-code-through-cmake-on-android-studio –
Whitefaced sdk/native/libs
folder, not the sdk/native
folder (the phrasing in the answer makes this easy to overlook) –
Mulderig include static{ System.loadLibrary("opencv_java"); }
where should I add this? –
Openminded Update build.gradle under imported OpenCV module to update 4 fields to match your project build.gradle a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and d) targetSdkVersio
there is no numbers to change. I use android studio v2.3 and only have this line with numbers ` classpath 'com.android.tools.build:gradle:2.3.0' ` –
Openminded /OpenCV-android-sdk/sdk/java
android studio not showing module name text box for edit, result module name import as java
. After that in dependencies there no java module showing, even after successfully importing the module –
Friesland sdk
for the module directory, not sdk/java
. –
Dahlberg static{}
block go? –
Dahlberg Integrating OpenCV v3.1.0 into Android Studio v1.4.1, instructions with additional detail and this-is-what-you-should-get type screenshots.
Most of the credit goes to Kiran, Kool, 1", and SteveLiles over at opencv.org for their explanations. I'm adding this answer because I believe that Android Studio's interface is now stable enough to work with on this type of integration stuff. Also I have to write these instructions anyway for our project.
Experienced A.S. developers will find some of this pedantic. This answer is targeted at people with limited experience in Android Studio.
Create a new Android Studio project using the project wizard (Menu:/File/New Project):
Blank Activity named MainActivity
You should have a cvtest1 directory where this project is stored. (the title bar of Android studio shows you where cvtest1 is when you open the project)
Verify that your app runs correctly. Try changing something like the "Hello World" text to confirm that the build/test cycle is OK for you. (I'm testing with an emulator of an API 19 device).
Download the OpenCV package for Android v3.1.0 and unzip it in some temporary directory somewhere. (Make sure it is the package specifically for Android and not just the OpenCV for Java package.) I'll call this directory "unzip-dir" Below unzip-dir you should have a sdk/native/libs directory with subdirectories that start with things like arm..., mips... and x86... (one for each type of "architecture" Android runs on)
From Android Studio import OpenCV into your project as a module: Menu:/File/New/Import_Module:
Click on next. You get a screen with three checkboxes and questions about jars, libraries and import options. All three should be checked. Click on Finish.
Android Studio starts to import the module and you are shown an import-summary.txt file that has a list of what was not imported (mostly javadoc files) and other pieces of information.
But you also get an error message saying failed to find target with hash string 'android-14'.... This happens because the build.gradle file in the OpenCV zip file you downloaded says to compile using android API version 14, which by default you don't have with Android Studio v1.4.1.
Open the project structure dialogue (Menu:/File/Project_Structure). Select the "app" module, click on the Dependencies tab and add :openCVLibrary310 as a Module Dependency. When you select Add/Module_Dependency it should appear in the list of modules you can add. It will now show up as a dependency but you will get a few more cannot-find-android-14 errors in the event log.
Look in the build.gradle file for your app module. There are multiple build.gradle files in an Android project. The one you want is in the cvtest1/app directory and from the project view it looks like build.gradle (Module: app). Note the values of these four fields:
Your project now has a cvtest1/OpenCVLibrary310 directory but it is not visible from the project view:
Use some other tool, such as any file manager, and go to this directory. You can also switch the project view from Android to Project Files and you can find this directory as shown in this screenshot:
Inside there is another build.gradle file (it's highlighted in the above screenshot). Update this file with the four values from step 6.
Resynch your project and then clean/rebuild it. (Menu:/Build/Clean_Project) It should clean and build without errors and you should see many references to :openCVLibrary310 in the 0:Messages screen.
At this point the module should appear in the project hierarchy as openCVLibrary310, just like app. (Note that in that little drop-down menu I switched back from Project View to Android View ). You should also see an additional build.gradle file under "Gradle Scripts" but I find the Android Studio interface a little bit glitchy and sometimes it does not do this right away. So try resynching, cleaning, even restarting Android Studio.
You should see the openCVLibrary310 module with all the OpenCV functions under java like in this screenshot:
Copy the {unzip-dir}/sdk/native/libs directory (and everything under it) to your Android project, to cvtest1/OpenCVLibrary310/src/main/, and then rename your copy from libs to jniLibs. You should now have a cvtest1/OpenCVLibrary310/src/main/jniLibs directory. Resynch your project and this directory should now appear in the project view under openCVLibrary310.
Go to the onCreate method of MainActivity.java and append this code:
if (!OpenCVLoader.initDebug()) {
Log.e(this.getClass().getSimpleName(), " OpenCVLoader.initDebug(), not working.");
} else {
Log.d(this.getClass().getSimpleName(), " OpenCVLoader.initDebug(), working.");
}
Then run your application. You should see lines like this in the Android Monitor: (I don't know why that line with the error message is there)
Now try to actually use some openCV code. In the example below I copied a .jpg file to the cache directory of the cvtest1 application on the android emulator. The code below loads this image, runs the canny edge detection algorithm and then writes the results back to a .png file in the same directory.
Put this code just below the code from the previous step and alter it to match your own files/directories.
String inputFileName="simm_01";
String inputExtension = "jpg";
String inputDir = getCacheDir().getAbsolutePath(); // use the cache directory for i/o
String outputDir = getCacheDir().getAbsolutePath();
String outputExtension = "png";
String inputFilePath = inputDir + File.separator + inputFileName + "." + inputExtension;
Log.d (this.getClass().getSimpleName(), "loading " + inputFilePath + "...");
Mat image = Imgcodecs.imread(inputFilePath);
Log.d (this.getClass().getSimpleName(), "width of " + inputFileName + ": " + image.width());
// if width is 0 then it did not read your image.
// for the canny edge detection algorithm, play with these to see different results
int threshold1 = 70;
int threshold2 = 100;
Mat im_canny = new Mat(); // you have to initialize output image before giving it to the Canny method
Imgproc.Canny(image, im_canny, threshold1, threshold2);
String cannyFilename = outputDir + File.separator + inputFileName + "_canny-" + threshold1 + "-" + threshold2 + "." + outputExtension;
Log.d (this.getClass().getSimpleName(), "Writing " + cannyFilename);
Imgcodecs.imwrite(cannyFilename, im_canny);
Run your application. Your emulator should create a black and white "edge" image. You can use the Android Device Monitor to retrieve the output or write an activity to show it.
The Gotchas:
OpenCV error: Cannot load info library for OpenCV
2 java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/www.deven.com.opencv-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libopencv_java3.so
What these error about i done step by step as you written. –
Goblet externalNativeBuild
or ndk
block is not found in build.gradle
file. Recent updates in Android Studio 2.3.0 has received that kind of integration. Please check my answer for more information: https://mcmap.net/q/145478/-adding-opencv-to-native-c-code-through-cmake-on-android-studio –
Whitefaced For everyone who felt they want to run away with all the steps and screen shots on the (great!) above answers, this worked for me with android studio 2.2.1
:
Create a new project, name it as you want and take the default (minSdkVersion 15 is fine).
Download the zip file from here: https://sourceforge.net/projects/opencvlibrary/files/opencv-android/ (I downloaded 3.2.0 version, but there may be a newer versions).
Unzip the zip file, the best place is in your workspace folder, but it not really matter.
Inside Android Studio
, click File->New-> Import Module
and navigate to \path_to_your_unzipped_file\OpenCV-android-sdk\sdk\java
and hit Ok, then accept all default dialogs.
In the gradle
file of your app
module, add this to the dependencies block:
dependencies {
compile project(':openCVLibraryXYZ')
//rest of code
}
Where XYZ is the exact version you downloaded, for example in my case:
dependencies {
compile project(':openCVLibrary320')
//rest of code
}
Android Studio 3.4 + OpenCV 4.1
Download the latest OpenCV zip file from here (current newest version is 4.1.0) and unzip it in your workspace or in another folder.
Create new Android Studio project normally. Click File->New->Import Module
, navigate to /path_to_unzipped_files/OpenCV-android-sdk/sdk/java
, set Module name as opencv
, click Next
and uncheck all options in the screen.
Enable Project
file view mode (default mode is Android
). In the opencv/build.gradle
file change apply plugin: 'com.android.application'
to apply plugin: 'com.android.library'
and replace application ID "org.opencv"
with
minSdkVersion 21
targetSdkVersion 28
(according the values in app/build.gradle
). Sync project with Gradle files.
Add this string to the dependencies block in the app/build.gradle
file
dependencies {
...
implementation project(path: ':opencv')
...
}
Select again Android
file view mode. Right click on app
module and goto New->Folder->JNI Folder
. Select change folder location and set src/main/jniLibs/
.
Select again Project
file view mode and copy all folders from /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/libs
to app/src/main/jniLibs
.
Again in Android
file view mode right click on app
module and choose Link C++ Project with Gradle
. Select Build System ndk-build
and path to OpenCV.mk
file /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/jni/OpenCV.mk
.
path_to_unzipped_files
must not contain any spaces, or you will get error!
To check OpenCV initialization add Toast message in MainActivity onCreate()
method:
Toast.makeText(MainActivity.this, String.valueOf(OpenCVLoader.initDebug()), Toast.LENGTH_LONG).show();
If initialization is successful you will see true
in Toast message else you will see false
.
application ID "org.opencv"
string with two strings: minSdkVersion 21
and targetSdkVersion 28
(according the values in app/build.gradle file) –
Lorie In your build.gradle
repositories {
jcenter()
}
implementation 'com.quickbirdstudios:opencv:4.1.0'
Download
Get the latest pre-built OpenCV for Android release from https://github.com/opencv/opencv/releases and unpack it (for example, opencv-4.4.0-android-sdk.zip).
Create an empty Android Studio project
Open Android Studio. Start a new project.
Keep default target settings.
Use "Empty Activity" template. Name activity as MainActivity with a corresponding layout activity_main. Plug in your device and run the project. It should be installed and launched successfully before we'll go next.
Add OpenCV dependency
Go to File->New->Import module
and provide a path to unpacked_OpenCV_package/sdk/java. The name of module detects automatically. Disable all features that Android Studio will suggest you on the next window.
Configure your library build.gradle (openCVLibrary build.gradle)
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
Implement the library to the project (application build.gradle)
implementation project(':openCVLibrary330')
This worked for me and was as easy as adding a gradle dependancy:
https://bintray.com/seesaa/maven/opencv#
https://github.com/seesaa/opencv-android
The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.
It seems to build and the suggested test:
static {
OpenCVLoader.initDebug();
}
spits out a bunch of output that looks about right to me.
On the latest openCV version 4.5.2, you need to import the whole sdk folder, not sdk/java, other wise when you go to add the dependency, OpenCV doesn't show up. full description here:
It took me a long time to figure out how it works. The method I used does not require Gradle.
Disclaimer: I do not know how good or bad this method is. So use it on your own.
Note that for both libraries you must place at least four files with the same name but in folders for different CPU architectures.
static {
System.loadLibrary("opencv_java4");
}
And for last TIP make an APK directly if you don't want to emulate your application.
I was able to install opencv 3.4.15 on Android studio Arctic Fox with just 3 steps:
def opencvsdk='/path/to/opencv-3.4.1-android-sdk/OpenCV-android-sdk'
include ':opencv'
project(':opencv').projectDir = new File(opencvsdk + '/sdk')
Hit Sync Now
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project(':opencv')
Hit Sync Now
Done !!!
Verification:
Add the below lines to your MainActivity.java
static {
String TAG = "MainActivity";
if (OpenCVLoader.initDebug()){
Log.i(TAG, "opencv installed successfully");
}else{
Log.i(TAG, "opencv not installed");
}
}
Source:
After you have extracted the zip file, go to the location below:
opencv-3.4.1-android-sdk/OpenCV-android-sdk/sdk and open build.gradle file with any text viewer. There if you scroll down you will find something similar to the screenshot below
In the latest OpenCV releases you need to import the whole sdk
folder.
Actually, it is pretty easy to import OpenCV by just following the official guide from its build.gradle
file. Here is a slightly edited version:
settings.gradle
(sdk
directory of OpenCV should be a subdirectory of the specified path):def opencvsdk='<path_to_opencv_android_sdk_rootdir>'
include ':opencv'
project(':opencv').projectDir = new File(opencvsdk + '/sdk')
app/build.gradle
:dependencies {
...
implementation project(':opencv')
}
System.loadLibrary("opencv_java4")
(the actual name depends on your OpenCV version) or OpenCVLoader.initDebug()
app/CMakeLists.txt
:find_package(OpenCV <your-opencv-version> REQUIRED java)
...
target_link_libraries(<your-native-lib-name> ${OpenCV_LIBRARIES})
app/build.gradle
:defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags "-std=c++11 -frtti -fexceptions"
arguments "-DOpenCV_DIR=" + opencvsdk + "/sdk/native/jni",
"-DANDROID_ARM_NEON=TRUE"
}
}
}
I am bit late. But I was also unable to load the latest version (v:4.5.5) of opencv sdk in android studio, because everyone was saying that File-> New-> Import Module-> then go to opencv-4.5.5-android-sdk\OpenCV-android-sdk\sdk\java folder, but when I imported, it seems to be nothing in my imported opencv module so after a long research I was able to find solution so here I have shared.
If you want to check that you have successfully added opencv. you can write below code in MainActivity.kt or MainActivity.java.
if (OpenCVLoader.initDebug()) {
Log.d("myTag", "OpenCV loaded")
}
Cheers!!
Anybody facing problemn while creating jniLibs cpp is shown ..just add ndk ..
Just add jcenter() to repositories in build gradle
repositories {
jcenter()
google()
mavenCentral()
}
then add this implementation
implementation 'com.quickbirdstudios:opencv:4.1.0'
© 2022 - 2024 — McMap. All rights reserved.
native
directory under mysdk
directory.Am I missing something? – Nardone