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

8
我想将字节数组转换为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)

这是我的代码:
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);

我尝试了很多方法,也进行了大量的搜索,但并没有找到任何解决方案。

注意: 我知道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());

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

提前感谢!

4个回答

30

我这样解决了这个问题:

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

现在它运行良好,比*bytes->BufferedImage->Mat*快得多。


2
Imgcodecs.CV_LOAD_IMAGE_UNCHANGED 宏已被 IMREAD_UNCHANGED 替换。 - Elif
你如何知道图像是否成功解码? - Tobiq
@Tobiq 检查返回的矩阵是否为空()? - Bahramdun Adil
@BahramdunAdil 我最终做到了,谢谢。 - Tobiq

0
请试一下。我正在使用这个。
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);

或者

OpenCV imread()

Mat myPic = Highgui.imread(url);

2
感谢您的回复,我知道这种方法。但是我想直接将字节转换为Mat,如果我们先将其转换为BufferedImage,然后再转换为Mat,那么它需要很多处理时间。这有点浪费时间。 - Bahramdun Adil
Mat myPic = Highgui.imread(url); 这个也不能用,因为我直接接收字节。 - Bahramdun Adil
Highgui已从OpenCv 3.0.0中删除,并被Imgcodecs替代。 - Ajay Sant

0
// 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);

-2

我尝试过这种解决方案。

 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; 

}

1
"我尝试过这种解决方案" - 成功了吗?还是遇到了一些问题? - mkl
你要返回什么?一个空的Mat吗?而ba是什么?在你的代码中哪里使用了mob?这段代码完全错误,甚至无法编译。最后,问题并没有提到如何将字节数组转换为BufferedImage,而是转换为Mat对象。 - Bahramdun Adil
抱歉兄弟,我要编辑代码。实际上我从我的项目中提取了错误的代码。现在请检查一下。 - Log Raj Bhatt
@LogRajBhatt,为什么你不像我在上面的答案中那样直接在ba上使用Imgcodecs.imdecode()呢?你的回答中没有新内容,最好的方法就是我上面所做的,不需要像你想的那样去做。 - Bahramdun Adil
哦,我明白了,前两行没有意义。我从完全不同的场景中提取了我的代码。 - Log Raj Bhatt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接