0

I am storing BufferedImages inside a MySQL database and retrieve them to a java application.

The BufferedImages are of type TYPE_INT_RGB.

How can i convert that image to a OpenCV Mat object?

I do always get a

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

Exception.

Can somebody help?

tellob
  • 1,220
  • 3
  • 16
  • 32

2 Answers2

2

Got it on my own.

    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 is the BufferedImage, you want to convert to a Mat-Object.

tellob
  • 1,220
  • 3
  • 16
  • 32
  • This example is very helpful, but I'm confused by all the buffers. Why create `intBuffer`? It doesn't seem like you use it. Perhaps the second-to-last line should read `mat.put(0, 0, intBuffer.array());`? Or can you just `mat.put` using the `byteBuffer` directly without creating the intermediate `intBuffer`? – Topher Mar 15 '14 at 07:01
  • To answer my own question, the `byteBuffer.asIntBuffer()` creates a view of the data (as opposed to a independent object), so the subsequent `intBuffer.put(data)` really does modify the data underlying `byteBuffer`. – Topher Mar 15 '14 at 07:04
0

A much more simplified version of tellob's 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;
}
Derek
  • 882
  • 1
  • 14
  • 36