java 如何在Java中将字节数组转换为Mat对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33493941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:45:20  来源:igfitidea点击:

How to convert byte array to Mat object in Java

javaopencv

提问by Bahramdun Adil

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

我想将字节数组转换为 Mat 对象,但它抛出

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

注意:我知道Imgcodecs.imread("aaa.jpg");并且

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.

但是我想直接将字节数组转换为 Mat 而不需要任何额外的过程来加快处理时间。

Thanks in advance!

提前致谢!

回答by Bahramdun Adil

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*

现在它运行良好并且比 *bytes->BufferedImage->Mat*

回答by Gurkan Yesilyurt

Try it please. I'm using this.

请尝试一下。我正在使用这个。

BufferedImage b = ImageIO.read(url);
BufferedImage b1 = new BufferedImage(b.getWidth(), b.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
b1=b;
byte [] pixels = ((DataBufferByte)b1.getRaster().getDataBuffer()).getData();

Mat myPic = new Mat(b1.getHeight(),b1.getWidth(),CvType.CV_8UC3);
myPic.put(0, 0, pixels);

Or

或者

OpenCV imread()

OpenCV imread()

Mat myPic = Highgui.imread(url);

回答by DerekDick

// OpenCV 3.x
Mat mat = Imgcodecs.imdecode(new MatOfByte(bytes), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
// OpenCV 2.x
Mat mat = Highgui.imdecode(new MatOfByte(bytes), Highgui.CV_LOAD_IMAGE_UNCHANGED);

回答by Log Raj Bhatt

I've tried this kind of solution.

我已经尝试过这种解决方案。

 static Mat ba2Mat(byte[] ba)throws Exception{
    // String base64String=Base64.getEncoder().encodeToString(ba);


      //  byte[] bytearray = Base64.getDecoder().decode(base64String);
        Mat mat = Imgcodecs.imdecode(new MatOfByte(ba), 
        Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
    return mat; 

}