如何在Java中将OpenCV Mat对象转换为BufferedImage对象?
如果您尝试使用OpenCV的**imread()**方法读取图像,它将返回一个Mat对象。如果您想使用AWT/Swing窗口显示生成的Mat对象的内容,则需要将Mat对象转换为java.awt.image.BufferedImage类的对象。为此,您需要按照以下步骤操作:
**将Mat编码为MatOfByte** - 首先,您需要将矩阵转换为字节矩阵。您可以使用Imgcodecs类的imencode()方法来实现。
此方法接受一个String参数(指定图像格式),一个Mat对象(表示图像),一个MatOfByte对象。
**将MatOfByte对象转换为字节数组** - 使用toArray()方法将MatOfByte对象转换为字节数组。
**实例化ByteArrayInputStream** - 通过将上一步中创建的字节数组传递给它的一个构造函数来实例化ByteArrayInputStream类。
**创建BufferedImage对象** - 将上一步中创建的InputStream对象传递给ImageIO类的read()方法。这将返回一个BufferedImage对象。
示例
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
public class Mat2BufferedImage {
public static BufferedImage Mat2BufferedImage(Mat mat) throws IOException{
//Encoding the image
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", mat, 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);
return bufImage;
}
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 = "C:/EXAMPLES/OpenCV/sample.jpg";
Mat image = Imgcodecs.imread(file);
BufferedImage obj = Mat2BufferedImage(image);
System.out.println(obj);
}
}输出
BufferedImage@579bb367: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1de0aca6 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 500 height = 360 #numDataElements 3 dataOff[0] = 2
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP