从位图转换为mat opencv android javacpp -presets opencv

时间:2018-04-06 15:34:22

标签: android opencv mat

我正在尝试使用来自org.bytedeco.javacpp-presets的opencv android从Bitmap转换为Mat:opencv:3.4.1-1.4.1

此版本的opencv似乎没有Utils.bitmapToMat或Utils.matToBitmap

这是我的代码。

Bitmap bradsFace = BitmapFactory.decodeResource(getResources(), R.drawable.brad_face);
int orgWidth = bradsFace.getWidth();
int orgHeight = bradsFace.getHeight();
int[] pixels = new int[orgWidth * orgHeight];
bradsFace.getPixels(pixels, 0, orgWidth, 0, 0, orgWidth, orgHeight);

Mat m = new Mat(orgHeight, orgWidth, CvType.CV_8UC4);

int id = 0;
for(int row = 0; row < orgHeight; row++) {
    for(int col = 0; col < orgWidth; col++) {
        int color = pixels[id];
        int a = (color >> 24) & 0xff; // or color >>> 24
        int r = (color >> 16) & 0xff;
        int g = (color >>  8) & 0xff;
        int b = (color      ) & 0xff;

        m.put(row, col, new int[]{a, r, g, b});
        id++;
     }
 }

在Mat对象的.put方法中,我的应用程序崩溃了。我做错了吗?

1 个答案:

答案 0 :(得分:0)

如果有人正在寻找在Android中将Mat转换为Bitmap的方法。我找到了一些东西。

public static Bitmap matToBitmap(Mat m) {
    int mWidth = m.width();
    int mHeight = m.height();
    int[] pixels = new int[mWidth * mHeight];
    int type = m.type();

    int index = 0;
    int a = 255;
    int b = 255;
    int g = 255;
    int r = 255;
    double[] abgr;

    Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);

    try {
        for (int ro = 0; ro < m.rows(); ro++) {
            for (int c = 0; c < m.cols(); c++) {
                abgr = m.get(ro, c);
                if(type == CvType.CV_8UC4) {
                    a = (int)abgr[0];
                    b = (int)abgr[1];
                    g = (int)abgr[2];
                    r = (int)abgr[3];
                } else if(type == CvType.CV_8UC3) {
                    a = 255;
                    b = (int)abgr[0];
                    g = (int)abgr[1];
                    r = (int)abgr[2];
                }
                int color = ((a << 24) & 0xFF000000) + 
                    ((r << 16) & 0x00FF0000) + 
                    ((g << 8) & 0x0000FF00) + 
                    (b & 0x000000FF);
                pixels[index] = color;
                index++;
            }
        }
        bitmap.setPixels(pixels, 0, mWidth, 0, 0, mWidth, mHeight);
    }catch(Exception e) {
        return bitmap;
    }
    return bitmap;
}