Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save image into Mat using Java?

Tags:

java

opencv

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.

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);
like image 664
Tleung Avatar asked Mar 02 '16 08:03

Tleung


1 Answers

It is all because the data type of the different images differ. For one you have DataBufferByte, for other you may have 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.

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.

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.

like image 86
Krzysztof Cichocki Avatar answered Oct 11 '22 10:10

Krzysztof Cichocki