将BufferedImage TYPE_INT_RGB转换为OpenCV Mat对象

时间:2014-01-16 23:51:31

标签: java opencv bufferedimage mat

我将BufferedImages存储在MySQL数据库中并将它们检索到java应用程序。

BufferedImages的类型为TYPE_INT_RGB。

如何将该图像转换为OpenCV Mat对象?

我总是得到一个

java.lang.UnsupportedOperationException: Mat data type is not compatible: 

异常。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

自己动手。

    int[] data = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
    ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4); 
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    intBuffer.put(data);

    Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
    mat.put(0, 0, byteBuffer.array());
    return mat;

image是BufferedImage,您想要转换为Mat-Object。

答案 1 :(得分:0)

更简化的tellob版本的orignal anwser。

public static Mat mat2(BufferedImage image)
{
    byte[] data = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
    Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
    mat.put(0, 0, data);
    return mat;
}