我试图从本机代码部分读取图像。 我用来从资源中提取文件的Java部分:
String unpackFileFromResources(int resID, String subdir, String fname)
{
String full_path = "";
try
{
// load cascade file from application resources
InputStream is = getResources().openRawResource(resID);
File cascadeDir = new File(Environment.getExternalStorageDirectory(), subdir);
if (!cascadeDir.exists())
{
cascadeDir.mkdirs();
}
mCascadeFile = new File(cascadeDir, fname);
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
full_path = mCascadeFile.getAbsolutePath();
} catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, "Failed to load cascade. Exception thrown: " + e);
}
return full_path;
}
OpenCV加载程序回调:
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this)
{
@Override
public void onManagerConnected(int status)
{
switch (status)
{
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
// Load native library after(!) OpenCV initialization
System.loadLibrary("mixed_sample");
String path = unpackFileFromResources(R.raw.lena, "cascade", "lena.jpg");
ReadFile(path);
}
break;
default:
{
super.onManagerConnected(status);
}
break;
}
}
};
原生部分:
#define LOG_TAG "MyLog"
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
JNIEXPORT void JNICALL Java_com_smorodov_opencv_MainActivity_ReadFile(JNIEnv* jenv, jobject, jstring jFileName)
{
const char* jnamestr = jenv->GetStringUTFChars(jFileName, NULL);
string stdFileName(jnamestr);
// This works perfect
ifstream fl(jnamestr);
fl.seekg(0, ios::end );
size_t len = fl.tellg();
char *ret = new char[len];
fl.seekg(0, ios::beg);
fl.read(ret, len);
fl.close();
delete[] ret;
// This returns empty matrix
Mat m=imread(stdFileName,0);
LOGD("%s",stdFileName.c_str());
LOGD("fl.read %d bytes",len);
LOGD("m.empty() = %d",m.empty());
}
当我运行此代码时,我得到输出:
/storage/emulated/0/cascade/lena.jpg 05-08 16:01:57.721:
D / MyLog(27433):fl.read 91814 bytes 05-08 16:01:57.721:
D / MyLog(27433):m.empty()= 1
问题是:是否可以从本机代码中读取图像/ Mat /级联。