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
Suppose image is my Mat object
So lets take an object of MatOfByte.
Now convert byte mat into array of bytes.
This is the complete snippet
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");Happy Coding!!! :)
MatOfByte bytemat = new MatOfByte();
Highgui.imencode(".jpg", image, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = ImageIO.read(in);
Interesting, thanks! Is this a .bmp type of image?
ReplyDeleteMy pleasure Sir !
ReplyDeleteThanks - helped me too.
ReplyDelete... but in the complete snippet it should read:
Highgui.imencode(".jpg", image, bytemat);
as it is in the text before.
Thanks for pointing it out. I have changed it.
DeleteThank u very much
ReplyDeletethank you, very solved problem
ReplyDeleteHey Sir now in opencv new version highgui is missing !!
ReplyDeleteuse ImgCodecs
Delete