如何使用 Swing 顯示 OpenCV Mat 物件?
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"); } }
輸出
執行時,上述程式將生成以下輸出 −
廣告