Java OpenCV - 如何直接从 Mat 制作 BufferedImage

Java OpenCV - how to make BufferedImage from Mat directly

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.VideoCapture;

public class Main {

  public static void main(String[] args) {
      System.out.println("Welcome to OpenCV " + Core.VERSION);
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
      VideoCapture vc = new VideoCapture(0);
      Mat m = new Mat(5,5, 0);
      vc.retrieve(m);
  }

我怎样才能从这个垫子上得到 BufferedImage。可能吗?如果不行请建议我一些其他的方法。

是的,有可能:

public static BufferedImage mat2Img(Mat in)
{
    BufferedImage out;
    byte[] data = new byte[320 * 240 * (int)in.elemSize()];
    int type;
    in.get(0, 0, data);

    if(in.channels() == 1)
        type = BufferedImage.TYPE_BYTE_GRAY;
    else
        type = BufferedImage.TYPE_3BYTE_BGR;

    out = new BufferedImage(320, 240, type);

    out.getRaster().setDataElements(0, 0, 320, 240, data);
    return out;
} 

reference