使用 Java 将图像保存到 Mat 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35742171/
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
Save image into Mat using Java?
提问by Tleung
Some bmp and tif image files cannot be read using the following method, except for the jpeg files. And I want to save it in opencv's Mat structure. What should I do? And I want to convert it into BufferedImage for further processing.
使用以下方法无法读取某些 bmp 和 tif 图像文件,但 jpeg 文件除外。我想将它保存在 opencv 的 Mat 结构中。我该怎么办?我想将其转换为 BufferedImage 以进行进一步处理。
File input = new File("C:\File\1.tif");
BufferedImage image = ImageIO.read(input);
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
Mat img = new Mat(image.getHeight(),image.getWidth(), CvType.CV_8UC3);
img.put(0, 0, data);
Imgcodecs.imwrite("C:\File\input.jpg", img);
回答by Krzysztof Cichocki
It is all because the data type of the different images differ. For one you have DataBufferByte, for other you may have DataBufferInt.
这都是因为不同图像的数据类型不同。对于一个你有 DataBufferByte,对于另一个你可能有 DataBufferInt。
You can create an new BufferedImage of same size with type 3BYTE_BGR, and then draw the original image into it, then you can construct a Mat from this new one.
您可以创建一个新的相同大小的 3BYTE_BGR 类型的 BufferedImage,然后将原始图像绘制到其中,然后您就可以从这个新图像构建一个 Mat。
You can also use different supported Mat image type instead of CvType.CV_8UC3, but that depends if there are equivalent types for java ones.
您还可以使用不同的受支持 Mat 图像类型而不是 CvType.CV_8UC3,但这取决于 java 是否有等效类型。
This is for the approach with conversion:
这是用于转换的方法:
File input = new File("C:\File\1.tif");
BufferedImage image = ImageIO.read(input);
// Here we convert into *supported* format
BufferedImage imageCopy =
new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
imageCopy.getGraphics().drawImage(image, 0, 0, null);
byte[] data = ((DataBufferByte) imageCopy.getRaster().getDataBuffer()).getData();
Mat img = new Mat(image.getHeight(),image.getWidth(), CvType.CV_8UC3);
img.put(0, 0, data);
Imgcodecs.imwrite("C:\File\input.jpg", img);
In the approach presented above you are delegating all the "conversion stuff" to the java BufferedImage and Graphics implementations. It is the easiest approach to have some standardized image format for any image. There is also another approach to tell java to directly load image as concrete type, but I don't remember the code right now, and it is far more complicated than this.
在上面介绍的方法中,您将所有“转换内容”委托给 java BufferedImage 和 Graphics 实现。为任何图像设置一些标准化的图像格式是最简单的方法。还有另一种方法告诉java直接将图像加载为具体类型,但我现在不记得代码了,而且它比这个复杂得多。