在Android中使用OpenCV从assets文件夹加载图像

5

我在尝试使用OpenCV 3.0在Android中加载放置在assets文件夹中的图像时遇到了困难。我已经阅读了很多答案,但是我无法弄清楚我做错了什么。

"my image.jpg"直接放置在由Android Studio创建的assets文件夹中。 这是我正在使用的代码。我已经检查过库是否正确加载。

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

当我尝试运行我的应用程序时,这就是我得到的结果:

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文件夹中加载,但无论如何都不起作用,我更愿意使用assets文件夹中的图片。

请问有谁能帮助我找到正确路径吗?

谢谢。

1个回答

5
问题:imread 需要绝对路径,而您的资源位于 apk 中,底层 c++ 类无法从中读取。
选项 1:从 drawable 文件夹加载图像到 Mat 中,而不使用 imread。
                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:将图像复制到缓存并从绝对路径加载。
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);
}

我按照你的建议使用了drawable文件夹,现在它可以正常工作了。谢谢! - andraga91

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接