ImageIcon 클래스는 이미지에서 아이콘을 그리는 Icon 인터페이스의 구현입니다. 이 클래스를 사용하여 Swing 창에 이미지를 표시할 수 있으며 이 클래스의 생성자는 BufferedImage 객체를 매개변수로 받습니다.
따라서 Swing 창을 사용하여 Mat 개체에 저장된 OpenCV 이미지를 표시하려면 BufferedImage 개체로 변환하여 ImageIcon 메서드에 매개변수로 전달해야 합니다.
예시
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
public class DisplayingImagesUsingSwings {
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 = "D:\\images\\tree.jpg";
Mat image = Imgcodecs.imread(file);
//Encoding the image
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", image, 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);
//Instantiate JFrame
JFrame frame = new JFrame();
//Set Content to the JFrame
frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
frame.pack();
frame.setVisible(true);
System.out.println("Image Loaded");
}
} 출력
실행 시 위의 프로그램은 다음과 같은 출력을 생성합니다. -
