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

时间:2015-01-04 21:51:37

标签: java opencv bufferedimage

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。可能吗?如果没有,请建议我一些其他的方法。

1 个答案:

答案 0 :(得分:2)

是的,可能:

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