imread可以在普通的c ++程序中工作,但不能在具有ndk本机的android系统中工作 [英] imread works in a normal c++ program, but not in android with ndk native

查看:140
本文介绍了imread可以在普通的c ++程序中工作,但不能在具有ndk本机的android系统中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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" );
    }
}

这就是我在android项目的Native Cpp部分中所拥有的.
当我使用模拟器运行应用程序时,它始终显示:"No data 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.

我已将此程序单独编译为普通的c ++ opencv程序.它工作正常.
我也给出了绝对的路径.这还不够吗?

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?

我也必须在build.gradle中写点东西吗?

Do I have to write something in build.gradle also?

如果这很重要,我正在使用Android Studio.

I am using Android studio, if that matters.

推荐答案

Android目录根本与Linux不匹配.

Android directories do not match Linux at all.

一个好的解决方案是通过Java查找文件,并将文件路径作为参数传递给函数Java_com_example_cppinandroid_MainActivity_stringFromJNI.

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.

如果文件是公共文件,则可以尝试"/sdcard/a.png"-但路径在不同的Android Shell之间可能会有所不同.

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" );
    }
}

一种更好的将图片存储在资产中并读取AAssetManager的方法,例如如何在Android中使用JNI将资产FileDescriptor正确传递到FFmpeg.

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.

这篇关于imread可以在普通的c ++程序中工作,但不能在具有ndk本机的android系统中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆