Reputation: 6079
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!
Upvotes: 8
Views: 21151
Reputation: 93
// 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);
Upvotes: 0
Reputation: 177
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;
}
Upvotes: -2
Reputation: 6079
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*
Upvotes: 31
Reputation: 2675
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()
Mat myPic = Highgui.imread(url);
Upvotes: 0