在Java中将BufferedImage转换为mat(OpenCV)



我已经尝试了这个链接,并有下面的代码。我的程序以 BufferedImage 格式导入图像,然后将其显示给用户。我在OpenCV中使用matchingTemplate函数,这需要我将其转换为Mat格式。

如果我导入图像 ->将其转换为 Mat 然后使用 imwrite 保存图像,则代码有效。该程序还允许用户裁剪图像,然后使用模板匹配将其与另一个图像进行比较。当我尝试将裁剪后的图像转换为 Mat 时出现问题,我需要使用以下代码将其从 Int 转换为字节:

im = new BufferedImage(im.getWidth(), im.getHeight(),BufferedImage.TYPE_3BYTE_BGR);

但是,这会导致黑色图像。但是如果我摆脱它,它仅适用于导入的图像而不适用于裁剪。这是怎么回事?我确定这与转换过程有关,因为我已经使用读取图像测试了模板匹配功能。

// Convert image to 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;
}

您可以尝试此方法,以实际将图像转换为TYPE_3BYTE_BGR(您的代码只是创建了一个相同大小的空白图像,这就是为什么它全黑的原因)。

用法:

// Convert any type of image to 3BYTE_BGR
im = toBufferedImageOfType(im, BufferedImage.TYPE_3BYTE_BGR);
// Access pixels as in original code

和转换方法:

public static BufferedImage toBufferedImageOfType(BufferedImage original, int type) {
    if (original == null) {
        throw new IllegalArgumentException("original == null");
    }
    // Don't convert if it already has correct type
    if (original.getType() == type) {
        return original;
    }
    // Create a buffered image
    BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), type);
    // Draw the image onto the new buffer
    Graphics2D g = image.createGraphics();
    try {
        g.setComposite(AlphaComposite.Src);
        g.drawImage(original, 0, 0, null);
    }
    finally {
        g.dispose();
    }
    return image;
}

最新更新