
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert OpenCV Mat to BufferedImage in Java
If you try to read an image using the OpenCV imread() method it returns a Mat object. If you want to display the contents of the resultant Mat object using an AWT/Swings window You need to convert the Mat object to an object of the class java.awt.image.BufferedImage. To do so, you need to follow the steps given below −
-
Encode the Mat to MatOfByte − First of all, you need to convert the matrix to the matrix of a byte. You can do it using the method imencode() of the class Imgcodecs.
This method accepts a String parameter(specifying the image format), a Mat object (representing the image), a MatOfByte object.
Convert the MatOfByte object to byte array − Convert the MatOfByte object into a byte array using the method toArray().
Instantiate ByteArrayInputStream − Instantiate the ByteArrayInputStream class by passing the byte array created in the previous step to one of its constructors.
Creating BufferedImage object − Pass the Input Stream object created in the previous step to the read() method of the ImageIO class. This will return a BufferedImage object.
Example
import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.imgcodecs.Imgcodecs; public class Mat2BufferedImage { public static BufferedImage Mat2BufferedImage(Mat mat) throws IOException{ //Encoding the image MatOfByte matOfByte = new MatOfByte(); Imgcodecs.imencode(".jpg", mat, matOfByte); //Storing the encoded Mat in a byte array byte[] byteArray = matOfByte.toArray(); //Preparing the Buffered Image InputStream in = new ByteArrayInputStream(byteArray); BufferedImage bufImage = ImageIO.read(in); return bufImage; } public static void main(String args[]) throws Exception { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the Image from the file String file = "C:/EXAMPLES/OpenCV/sample.jpg"; Mat image = Imgcodecs.imread(file); BufferedImage obj = Mat2BufferedImage(image); System.out.println(obj); } }
Output
BufferedImage@579bb367: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1de0aca6 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 500 height = 360 #numDataElements 3 dataOff[0] = 2