如何使用Java将OpenCV Mat对象转换为BufferedImage对象?

如果尝试使用OpenCV imread()方法读取图像,它将返回Mat对象。如果要使用AWT / Swings窗口显示生成的Mat对象的内容,则需要将Mat对象转换为类java.awt.image.BufferedImage的对象。为此,您需要遵循以下步骤-

  • 将Mat编码为MatOfByte-首先,您需要将矩阵转换为字节矩阵。您可以使用imencode()Imgcodecs类的方法来实现。

    此方法接受String参数(指定图像格式),Mat对象(代表图像),MatOfByte对象。

  • 将MatOfByte对象转换为字节数组-使用方法将MatOfByte对象转换为字节数组toArray()

  • 实例化ByteArrayInputStream- 通过将在上一步中创建的字节数组传递给其构造函数之一来实例化ByteArrayInputStream类。

  • 创建BufferedImage对象-将上一步中创建的Input Stream对象传递给read()ImageIO类的方法。这将返回一个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{
      //编码图像
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", mat, matOfByte);
      //将编码的Mat存储在字节数组中
      byte[] byteArray = matOfByte.toArray();
      //准备缓冲图像
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);
      return bufImage;
   }
   public static void main(String args[]) throws Exception {
      //加载OpenCV核心库
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //从文件中读取图像
      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