java - 在 OpenCV 中将 BufferedImage 转换为 Mat

标签 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,pixels);

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

最佳答案

这对我有用

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;
}

关于java - 在 OpenCV 中将 BufferedImage 转换为 Mat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36723594/

相关文章:

java - 在 Valid Anagram 程序中没有通过所有测试用例

java - Camel : Implementing Polling and Non-Polling Consumer within the same component

java - 是否可以将辅助注入(inject)和映射注入(inject)与Guice结合使用?

java - 如果我有一个window.open,我会丢失我的cookie吗?

python - 将 KNN 火车从 Opencv 3 转换为 2

java - 编辑翻转计数器以运行其他程序

opencv - project1.exe中0x52f9e470处未处理的异常:0xC000001D:非法指令

python - np.fft.ifft2 将图像完全变黑

python - 使用 Numpy 或 OpenCV 将图像中的剪切内容复制到新图像

python - Opencv:TypeError:轮廓不是numpy数组,也不是标量