Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert byte array to Mat object in Java

Tags:

java

opencv

I want to convert byte array to Mat object, but it throws

java.lang.UnsupportedOperationException: Provided data element number (60181) should be multiple of the Mat channels count (3)
    at org.opencv.core.Mat.put(Mat.java:992)

It is my code:

byte[] bytes = FileUtils.readFileToByteArray(new File("aaa.jpg"));

Mat mat = new Mat(576, 720, CvType.CV_8UC3);
//Imgcodecs.imencode(".jpg", mat, new MatOfByte(bytes));
mat.put(0, 0, bytes);

I tried many ways and also googled a lot, but did not find any solution.

Note: I know Imgcodecs.imread("aaa.jpg"); and

BufferedImage img = ImageIO.read(new ByteArrayInputStream(byteArray));
Mat mat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC3);
mat.put(0, 0, ((DataBufferByte) img.getRaster().getDataBuffer()).getData());

But I want to directly convert byte array to Mat without any extra process to speed up the process time.

Thanks in advance!

like image 813
Bahramdun Adil Avatar asked Nov 03 '15 07:11

Bahramdun Adil


1 Answers

I solved the problem like this:

byte[] bytes = FileUtils.readFileToByteArray(new File("aaa.jpg"));
Mat mat = Imgcodecs.imdecode(new MatOfByte(bytes), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);

Now it works well and much faster than *bytes->BufferedImage->Mat*

like image 176
Bahramdun Adil Avatar answered Oct 20 '22 09:10

Bahramdun Adil