Mat from byte-array (or stream) - which type/format?

asked 2014-02-25 01:57:56 -0600

Nagilo gravatar image

updated 2014-02-25 02:01:41 -0600

berak gravatar image

In my Android app I'm streaming images (all of same size) over the network to the Android device. Usually the stream is then decoded into a Bitmap like this:

            Bitmap bmp = BitmapFactory.decodeByteArray(buffer, 0,
                    buffer.length);

But this allocated and de-allocates memory all the time. Therefore I would prefer creating an OpenCV Mat and put the received buffer (byte[]) into that. But I just get a white-noise image because my image format seems wrong. Maybe you can help me? On the senders side (.NET C#) it's a PNG with 24bppRgb. On the receivers side (Android) I'm currently initializing the Mat like this:

            Mat mat = new Mat(new Size(width, height), CvType.CV_8U);                               
            mat.put(0, 0, buffer);
edit retag flag offensive close merge delete

Comments

i think your idea is broken.

if buffer is what you get from the stream, you still have to decode it first, no matter if you want a bitmap or a Mat as output.

http://docs.opencv.org/java/org/opencv/highgui/Highgui.html#imdecode(org.opencv.core.Mat,%20int)

but as you see, same problem here, imdecode will create a new Mat ...

berak gravatar imageberak ( 2014-02-25 02:07:05 -0600 )edit

You are right. But can you provide a sample code for that?

Nagilo gravatar imageNagilo ( 2014-02-25 02:09:29 -0600 )edit

byte[] buffer; // read from stream ..

Mat ocvImg = Highgui.imdecode(new MatOfByte(buffer), Highgui.IMREAD_UNCHANGED);

berak gravatar imageberak ( 2014-02-25 02:14:18 -0600 )edit

Nice, works fine ;) If you post your code as an answer, I will check it so that you get the reputation.

Nagilo gravatar imageNagilo ( 2014-02-25 02:21:55 -0600 )edit

You can also do:

byte[] buffer; // read from stream ..
ocvImg.put(0, 0, buffer);

instead of the imdecode, it is more straightforward.

Rui Marques gravatar imageRui Marques ( 2014-02-26 09:19:02 -0600 )edit

@Rui Marques, no. it's a compressed png (headers and all, not pixels) inside the buffer

berak gravatar imageberak ( 2014-02-26 09:21:37 -0600 )edit

Yes sorry, I was assuming a buffer filled with the pixels only.

Rui Marques gravatar imageRui Marques ( 2014-02-26 12:19:49 -0600 )edit

@Nagilo: Hi I was wondering if you would be willing to share the code of your android app? Thanks

mladem gravatar imagemladem ( 2014-07-14 16:08:33 -0600 )edit