【问题标题】:Load images with OpenCV from assets folder in Android使用 OpenCV 从 Android 中的资产文件夹加载图像
【发布时间】:2016-12-28 05:25:11
【问题描述】:

我试图在 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

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

谢谢

【问题讨论】:

    标签: android opencv imread


    【解决方案1】:

    问题: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);
    }
    

    【讨论】:

    • 我已经按照您的建议使用了可绘制文件夹,现在它可以工作了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 2021-08-19
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2017-08-05
    相关资源
    最近更新 更多