HimalayanCoder
HimalayanCoder

Reputation: 9850

Convert ByteBuffer to OpenCV Mat

I want to convert Bytebuffer to OpenCV Mat is an efficient manner.

The dirty solution is to first create a bitmap using copyPixelsFromBuffer

Bitmap bmp = Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(frame);

and then convert Bitmap to Mat using OpenCV utils.

Mat mat = new Mat();
Utils.bitmapToMat(bmp, mat);

which is slow

Please help me with an elegant solution

Upvotes: 1

Views: 5750

Answers (4)

enterML
enterML

Reputation: 2285

This is pretty easy with the below solution. Assuming that frame is the input ByteBuffer

byte[] data = new byte[frame.capacity()];
((ByteBuffer) frame.duplicate().clear()).get(data);
Mat mat = new Mat(480, 640, CvType.CV_8UC4);
mat.put(0, 0, data);

Upvotes: 1

dementor
dementor

Reputation: 85

This might be useful.

byte[] bytes = frame.array();      
Mat mat = Imgcodecs.imdecode(new MatOfByte(bytes), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);

Upvotes: 0

Mills
Mills

Reputation: 385

I'm not very familiar with ByteBuffer but if you can get a pointer to the buffer (via GetDirectBufferAddress()?), you can use this Mat constructor Mat(Size size, int type, void* data, size_t step) that will not do any copying.

Upvotes: 0

zindarod
zindarod

Reputation: 6468

Disclaimer: this is untested code.

If you know the properties (width,height,type etc) of the image then you could.

byte[] data = byteBuffer.array()
Mat mat = new Mat(width, height, CvType.CV_8UC3);
mat.put(0, 0, data);

Keep in mind that OpenCV creates images as B,G,R by default.

Upvotes: 2

Related Questions