How to convert an Image to Mat Android

4.8k views Asked by At

I need to process Image for my Application. I get the Images for ImageReader.

reader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Image mImage = reader.acquireNextImage();

                //mImage to Mat here

                mImage.close();
            }
        },null);

But now, I need to convert those images in Mat. I know that I can pass by the Bitmap class, but i don't know how to convert an Image into Bitmap too.

2

There are 2 answers

3
Widea On BEST ANSWER

I think that i found a possible answer. I give to my ImageReader a simple plane format like JPEG.

reader = ImageReader.newInstance(previewSize.getWidth(),previewSize.getHeight(), ImageFormat.JPEG, 2);

Then i do that :

ByteBuffer bb = image.getPlanes()[0].getBuffer();
    byte[] buf = new byte[bb.remaining()];
    bb.get(buf);

    imageGrab = new Mat();
    imageGrab.put(0,0,buf);
0
Mingjiang Shi On

Try this

// image to byte array
ByteBuffer bb = image.getPlanes()[0].getBuffer();
byte[] data = new byte[bb.remaining()];
bb.get(data);

// byte array to mat
Mat = Imgcodecs.imdecode(new MatOfByte(data), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);