Save image into Mat using Java?

13,169

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.

Share:
13,169
Tleung
Author by

Tleung

Updated on June 13, 2022

Comments

  • Tleung
    Tleung almost 2 years

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