imread works in a normal c++ program, but not in android with ndk native

给你一囗甜甜゛ 提交于 2020-05-17 08:49:18

问题


#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.


回答1:


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.



来源:https://stackoverflow.com/questions/61697669/imread-works-in-a-normal-c-program-but-not-in-android-with-ndk-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!