功能列表
- 将 opencv 中的 Mat 对象转为 Java 中的 BufferedImage 对象;
- 预览指定图像;
相关依赖
OpenCV 2.3.14
源代码
package com.dotions.opencv;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.opencv.core.Mat;
/**
* 图像相关工具类
*
* Created by wyf0931 on 2018-03-22.
*/
public class ImageUtil {
/**
* 预览指定的图像
*
* @param image
*/
public static void preview(Mat imageMat) {
BufferedImage image = mat2BufferedImage(imageMat);
preview(image);
}
/**
* 预览指定的图像
*
* @param image
*/
public static void preview(BufferedImage image) {
JFrame frame = new JFrame();
frame.setTitle("Preview");
frame.setBounds(20, 20, image.getWidth(), image.getHeight());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel label = new JLabel();
label.setBounds(0, 0, image.getWidth(), image.getHeight());
frame.getContentPane().add(label);
label.setIcon(new ImageIcon(image));
frame.setVisible(true);
}
/**
* 预览指定的图像
*
* @param filename
* @throws IOException
*/
public static void preview(String filename) throws IOException {
File image = new File(filename);
preview(image);
}
/**
* 预览指定的图像
*
* @param filename
* @throws IOException
*/
public static void preview(File image) throws IOException {
BufferedImage bufferedImage = ImageIO.read(image);
preview(bufferedImage);
}
/**
* 将 opencv 中 Mat 对象转为 Java 中的 BufferedImage 对象。
*
* @param mat
*/
public static BufferedImage mat2BufferedImage(Mat mat) {
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize();
byte[] data = new byte[cols * rows * elemSize];
int type;
mat.get(0, 0, data);
switch (mat.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 image = new BufferedImage(cols, rows, type);
image.getRaster().setDataElements(0, 0, cols, rows, data);
return image;
}
}
网友评论