Let's display the OpenCV processing result on the GUI using Swing.
It is a GUI toolkit for Java and is an extension of AWT. The GUI created by Swing draws with its own GUI component without relying on the OS component. The advantage is that it can be used regardless of the execution environment. The disadvantage is that the operation process is slow because it is no longer an OS component.
BufferedImage is used in this paper to display an image on Swing from Mat type. BudderedImage is image data with an accessible buffer and consists of ColorModel and Raster. The number and type of bands in the Raster SampleModel must match the number and type required for the ColorModel to represent its color and alpha value. The (0,0) coordinates are in the upper left corner. Therefore, Raster must be minX = 0, minY = 0.
Introduce the following: ・ Java development environment ・ OpenCV3.1
If you look it up, you will see various explanation pages in Japanese, so I will omit it.
The processing part is as follows.
Mat2Image
public static BufferedImage Mat2Image(Mat src) {
//Get the number of channels in Mat src
int type = 0;
if (src.channels() == 1) {
type = BufferedImage.TYPE_BYTE_GRAY;
} else if (src.channels() == 3) {
type = BufferedImage.TYPE_3BYTE_BGR;
} else {
return null;
}
//Create a new BufferedImage type with src width, length, and number of channels.
BufferedImage image = new BufferedImage(src.width(), src.height(), type);
//Extract Raster from the created BufferedImage.
WritableRaster raster = image.getRaster();
//Extract the buffer from the extracted Raster.
DataBufferByte Buf = (DataBufferByte) raster.getDataBuffer();
byte[] data = Buf.getData();
src.get(0, 0, data);
return image;
}
If you call this and put .setIcon on the Label of Swing, it will be displayed.
SetIcon
lblNewLabel = new JLabel();
ImageIcon image = new ImageIcon(createAwtImage(src));
lblNewLabel.setIcon(image);
I was able to display the Mat type image read by Imread on the GUI safely.
The source of the GUI for displaying images created this time is here. https://github.com/JackdMasaki/Mad2Image/blob/master/Mat2Imagetest.java
I referred to the following page when creating this article. I am deeply grateful. http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/ https://docs.oracle.com/javase/8/docs/api/index.html?java/awt/image/BufferedImage.html
Recommended Posts