OpenCV imread()를 사용하여 이미지를 읽으려고 하면 메서드는 Mat 객체를 반환합니다. AWT/Swings 창을 사용하여 결과 Mat 객체의 내용을 표시하려면 Mat 객체를 java.awt.image.BufferedImage 클래스의 객체로 변환해야 합니다. 이렇게 하려면 아래에 제공된 단계를 따라야 합니다. -
-
매트를 MatOfByte로 인코딩 − 먼저 행렬을 바이트의 행렬로 변환해야 합니다. Imgcodecs 클래스의 imencode() 메서드를 사용하여 수행할 수 있습니다.
이 메서드는 String 매개변수(이미지 형식 지정), Mat 개체(이미지 표현), MatOfByte 개체를 받습니다.
-
MatOfByte 개체를 바이트 배열로 변환 − toArray() 메서드를 사용하여 MatOfByte 객체를 바이트 배열로 변환합니다.
-
ByteArrayInputStream 인스턴스화 − 이전 단계에서 생성된 바이트 배열을 생성자 중 하나로 전달하여 ByteArrayInputStream 클래스를 인스턴스화합니다.
-
BufferedImage 개체 만들기 − 이전 단계에서 생성한 Input Stream 객체를 ImageIO 클래스의 read() 메서드에 전달합니다. BufferedImage 개체를 반환합니다.
예
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);
}
} 출력
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