使用Java將圖像保存到Mat?

[英]Save image into Mat using Java?


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.

除了jpeg文件之外,使用以下方法無法讀取某些bmp和tif圖像文件。我想將它保存在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);

1 个解决方案

#1


3  

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直接加載圖像作為具體類型,但我現在不記得代碼,它比這復雜得多。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/03/02/72f23d202f010d03dfc00aee13e7cde4.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com