Thursday 15 August 2013

Converting OpenCV Mat to BufferedImage of Java

While working with opencv and java i got stuck on how to display an image in java's JFrame, because i can't directly put Mat object of opencv in drawImage function of Java's Graphics class, so i need a hack to convert Mat object into BufferedImage which is as follows.
First think of how can we do it, we have some methods to make a BufferedImage such as
  • Directly passing the path of image, which is not the case.
  • Passing stream of bytes of image into BufferedImage, which can be useful, lets focus on it.

Suppose image is my Mat object
Mat image = Highgui.imread("/Users/Sumit/Desktop/image.jpg");
and i want to convert it into BufferedImage
So lets take an object of MatOfByte.
MatOfByte bytemat = new MatOfByte();
byte mat is to convert image into stream of bytes.
Highgui.imencode(".jpg", image, bytemat);
this will put the bytes into bytemat object
Now convert byte mat into array of bytes.
byte[] bytes = bytemat.toArray();
Pass these bytes into ByteArrayInputStream to get a stream of bytes.
InputStream in = new ByteArrayInputStream(bytes);
Now pass this stream in read method of ImageIO class.
BufferedImage img = ImageIO.read(in);
Now we have BufferedImage object, we can use it to display it in JFrame's paint method.

This is the complete snippet
Mat image = Highgui.imread("/Users/Sumit/Desktop/image.jpg");
MatOfByte bytemat = new MatOfByte();
Highgui.imencode(".jpg", image, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = ImageIO.read(in);
Happy Coding!!! :)

8 comments:

  1. Interesting, thanks! Is this a .bmp type of image?

    ReplyDelete
  2. Thanks - helped me too.

    ... but in the complete snippet it should read:

    Highgui.imencode(".jpg", image, bytemat);

    as it is in the text before.

    ReplyDelete
    Replies
    1. Thanks for pointing it out. I have changed it.

      Delete
  3. Hey Sir now in opencv new version highgui is missing !!

    ReplyDelete