【问题标题】:Convert BufferedImage TYPE_INT_RGB to OpenCV Mat Object将 BufferedImage TYPE_INT_RGB 转换为 OpenCV Mat 对象
【发布时间】:2015-06-16 23:01:31
【问题描述】:

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

BufferedImage 的类型为 TYPE_INT_RGB。

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

我总是得到一个

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

例外。

有人可以帮忙吗?

【问题讨论】:

    标签: java opencv bufferedimage mat


    【解决方案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。

    【讨论】:

    • 这个例子很有帮助,但我对所有的缓冲区感到困惑。为什么要创建intBuffer?你好像没用过。也许倒数第二行应该是mat.put(0, 0, intBuffer.array());?或者你可以直接使用byteBuffermat.put而不创建中间intBuffer吗?
    • 为了回答我自己的问题,byteBuffer.asIntBuffer() 创建了一个数据视图(而不是一个独立的对象),因此后续的intBuffer.put(data) 确实修改了byteBuffer 底层的数据。
    【解决方案2】:

    tellob 的原始答案的简化版本。

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

    【讨论】:

    • BufferedImage.TYPE_INT_RGB 将失败
    猜你喜欢
    • 2015-01-21
    • 2017-02-19
    • 2017-12-15
    • 2013-08-27
    • 2014-03-11
    • 2015-01-04
    • 2019-09-12
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多