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

时间:2016-08-21 16:21:48

标签: android opencv imread

我试图在Android中使用OpenCV 3.0加载放置在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

好像图片没有尺寸。我猜是因为它没有正确加载。我还尝试将其加载到可绘制的文件夹中,但它无论如何都不起作用,我更喜欢使用资产。 任何人都可以帮助我,告诉我如何找到正确的图像路径?

由于

1 个答案:

答案 0 :(得分:2)

问题:imread需要绝对路径,你的资产在apk中,而底层的c ++类无法从那里读取。

选项1:在不使用可绘制文件夹的imread的情况下将图像加载到Mat中。

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