在OpenCV中将BufferedImage转换为Mat

时间:2016-04-19 15:57:55

标签: java opencv

当我尝试使用此函数将BufferedImage转换为Mat时。

public Mat matify(BufferedImage im) {
// Convert INT to BYTE
//im = new BufferedImage(im.getWidth(), im.getHeight(),BufferedImage.TYPE_3BYTE_BGR);
// Convert bufferedimage to byte array
byte[] pixels = ((DataBufferByte) im.getRaster().getDataBuffer())
        .getData();

// Create a Matrix the same size of image
Mat image = new Mat(im.getHeight(), im.getWidth(), CvType.CV_8UC3);
// Fill Matrix with image values
image.put(0, 0, pixels);

return image;

}

我收到此错误。

Exception in thread "main" java.lang.UnsupportedOperationException: Provided data element number (7955216) should be multiple of the Mat channels count (3)
at org.opencv.core.Mat.put(Mat.java:2549)
at Main.matify(Main.java:78)
at Main.doOpenCV(Main.java:48)
at Main.main(Main.java:40)

错误是由此行引起的

image.put(0,0,像素);

为什么我收到此错误?如何在java中将BufferedImage转换为opencv Mat?

1 个答案:

答案 0 :(得分:0)

这对我有用

public Mat bufferedImageToMat(BufferedImage bi) {
    Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CV_8UC(3));

    int r, g, b;
    UByteRawIndexer indexer = mat.createIndexer();
    for (int y = 0; y < bi.getHeight(); y++) {
        for (int x = 0; x < bi.getWidth(); x++) {
            int rgb = bi.getRGB(x, y);

            r = (byte) ((rgb >> 0) & 0xFF);
            g = (byte) ((rgb >> 8) & 0xFF);
            b = (byte) ((rgb >> 16) & 0xFF);

            indexer.put(y, x, 0, r);
            indexer.put(y, x, 1, g);
            indexer.put(y, x, 2, b);
        }
    }
    indexer.release();
    return mat;
}