#include <jni.h>
#include <string>
#include <opencv2/opencv.hpp>
using namespace cv;
#include <iostream>
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_cppinandroid_MainActivity_stringFromJNI( JNIEnv* env,
jobject)
{
Mat image;
image = imread( "/home/<name>/a.png", 1 );
if ( !image.data )
{
return env->NewStringUTF( "No data in image!" );
} else
{
return env->NewStringUTF( "Data is in image" );
}
}
That's what I have in Native Cpp part of the android project.
When I run the application with emulator, it always shows: "No data in image!"
text.
I have compiled this program separately as a normal c++ opencv program. It is working perfectly fine.
I have given the absolute path too. Is that not enough?
Do I have to write something in build.gradle
also?
I am using Android studio, if that matters.
Android directories do not match Linux at all.
A good solution is to find your file through Java and pass the path to the file as a parameter to function Java_com_example_cppinandroid_MainActivity_stringFromJNI.
If your file is in public files, you can try "/sdcard/a.png" - but the path may vary between different android shells.
The possible solution from reading from public files:
Java:
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + fileName);
if (f.exists()) {
foo(f.getAbsolutePath());
NDK:
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_cppinandroid_MainActivity_stringFromJNI(JNIEnv* env,
jobject, jstring javaPath)
{
const char* path = env->GetStringUTFChars(javaPath, 0);
Mat image;
image = imread( path, 1 );
env->ReleaseStringUTFChars(javaPath, path );
if ( !image.data )
{
return env->NewStringUTF( "No data in image!" );
} else
{
return env->NewStringUTF( "Data is in image" );
}
}
A better way to store a picture in assets and read AAssetManager like Android read text file from asset folder using C (ndk) or How to properly pass an asset FileDescriptor to FFmpeg using JNI in Android .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.