问题描述
我在尝试使用Android中的OpenCV 3.0加载放置在资产文件夹中的图像时遇到了麻烦.我在这里读了很多答案,但是我无法弄清楚自己在做什么错.
I'm stuck trying to load an image placed in assets folder with OpenCV 3.0 in Android. I've read a lot of answers here, but I can't figure out what I'm doing wrong.
我的image.jpg"直接放置在Android Studio创建的资产文件夹中.这是我正在使用的代码.我已经检查过,并且库已正确加载.
"my image.jpg" is place directly in the assets folder created by Android Studio.This is the code I'm using. I've checked and the library has been loaded correctly.
Mat imgOr = Imgcodecs.imread("file:///android_asset/myimage.jpg");
int height = imgOr.height();
int width = imgOr.width();
String h = Integer.toString(height);
String w = Integer.toString(width);
if (imgOr.dataAddr() == 0) {
// If dataAddr() is different from zero, the image has been loaded
// correctly
Log.d(TAG, "WRONG UPLOAD");
}
Log.d(h, "height");
Log.d(w, "width");
当我尝试运行我的应用程序时,这就是我得到的:
When I try to run my app, this is what I get:
08-21 18:13:32.084 23501-23501/com.example.android D/MyActivity: WRONG UPLOAD
08-21 18:13:32.085 23501-23501/com.example.android D/0: height
08-21 18:13:32.085 23501-23501/com.example.android D/0: width
图像似乎没有尺寸.我猜是因为它没有正确加载.我还尝试加载它,将其放置在drawable文件夹中,但是无论如何它都无法正常工作,我更喜欢使用资产之一.任何人都可以帮助我,告诉我如何找到正确的图像路径?
It seems like the image has no dimensions. I guess because it has not been loaded correctly. I'va also tried to load it placing it in the drawable folder, but it doesn't work anyway and I'd prefer to use the assets one.Anyone can please help me and tell me how to find the right path of the image?
谢谢
推荐答案
问题:imread需要绝对路径,并且您的资产位于apk内,并且基础c ++类无法从那里读取.
Problem: imread needs absolute path and your assets are inside a apk, and the underlying c++ classes cannot read from there.
选项1:在不使用可绘制文件夹中的读取的情况下,将图像加载到Mat中.
Option 1: load image into Mat without using imread from drawable folder.
InputStream stream = null;
Uri uri = Uri.parse("android.resource://com.example.aaaaa.circulos/drawable/bbb_2");
try {
stream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bmp = BitmapFactory.decodeStream(stream, null, bmpFactoryOptions);
Mat ImageMat = new Mat();
Utils.bitmapToMat(bmp, ImageMat);
选项2:将图片复制到缓存并从绝对路径加载.
Option 2: copy image to cache and load from absolute path.
File file = new File(context.getCacheDir() + "/" + filename);
if (!file.exists())
try {
InputStream is = context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer);
fos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
if (file.exists()) {
image = cvLoadImage(file.getAbsolutePath(), type);
}
这篇关于使用OpenCV从Android中的Assets文件夹加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!