【Java Opencv系列】4.2在窗体中显示图像

时间:2023-01-20 08:57:49

4.2在窗体中显示图像

本节内容代码下载链接:http://download.csdn.net/detail/u012343179/9797262

在testOpencv项目的imageIO包中新建ShowImage.java窗体应用

【Java Opencv系列】4.2在窗体中显示图像

在Design面板中拖一个JLabel控件到窗体中(不会的话可以看1.2节)

切换到source面板,代码如下:
package imageIO;

import java.awt.EventQueue;
import java.awt.image.BufferedImage;

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.imgcodecs.Imgcodecs;

import tool.mat2BufferedImage;

public class ShowImage {

static{System.loadLibrary(Core.NATIVE_LIBRARY_NAME);}

private JFrame frame;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ShowImage window = new ShowImage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public ShowImage() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 800, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

JLabel label = new JLabel("");
label.setBounds(0, 0, 800, 450);
frame.getContentPane().add(label);

Mat source=Imgcodecs.imread("F://lena.jpg");//加载lena图像为Mat格式
BufferedImage image=mat2BufferedImage.matToBufferedImage(source);
label.setIcon(new ImageIcon(image));
}

}

注意:mat2BufferedImage.matToBufferedImage(source);这个方法是将Opencv中Mat格式的图像转换成Java Swing中的BufferedImage格式,因为在Swing中只支持BufferedImage格式图像显示。该方法是我们自己写的,又因为该方法我们以后一直要使用,因此,在testOpencv中新建一个tool包,然后在该包下新建一个mat2BufferedImage.java类,该类代码如下:

package tool;

import java.awt.image.BufferedImage;

import org.opencv.core.Mat;

public class mat2BufferedImage {
public static BufferedImage matToBufferedImage(Mat matrix) {
int cols = matrix.cols();
int rows = matrix.rows();
int elemSize = (int) matrix.elemSize();
byte[] data = new byte[cols * rows * elemSize];
int type;
matrix.get(0, 0, data);
switch (matrix.channels()) {
case 1:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
case 3:
type = BufferedImage.TYPE_3BYTE_BGR;
// bgr to rgb
byte b;
for (int i = 0; i < data.length; i = i + 3) {
b = data[i];
data[i] = data[i + 2];
data[i + 2] = b;
}
break;
default:
return null;
}
BufferedImage image2 = new BufferedImage(cols, rows, type);
image2.getRaster().setDataElements(0, 0, cols, rows, data);
return image2;
}
}

然后我们运行ShowImage.java

结果如下:

【Java Opencv系列】4.2在窗体中显示图像

女神就显示在我们的窗体上了。

CommissarMa      2017年3月28日19:53:30