在Java中将BuffereImage转换为Mat(OpenCV)

在Java中将BuffereImage转换为Mat(OpenCV),java,image,opencv,image-processing,bufferedimage,Java,Image,Opencv,Image Processing,Bufferedimage,我已经试过了,下面有代码。我的程序以BuffereImage格式导入图像,然后将其显示给用户。我正在使用OpenCV中的函数,该函数要求我将其转换为Mat格式 如果我导入图像->将其转换为Mat,然后使用imwrite保存图像,则代码可以工作。该程序还允许用户裁剪图像,然后使用将其与另一图像进行比较。当我试图将裁剪后的图像转换为Mat时,出现了问题。我需要使用以下代码将其从Int转换为Byte: im = new BufferedImage(im.getWidth(), im.getHeight

我已经试过了,下面有代码。我的程序以BuffereImage格式导入图像,然后将其显示给用户。我正在使用OpenCV中的函数,该函数要求我将其转换为Mat格式

如果我导入图像->将其转换为Mat,然后使用imwrite保存图像,则代码可以工作。该程序还允许用户裁剪图像,然后使用将其与另一图像进行比较。当我试图将裁剪后的图像转换为Mat时,出现了问题。我需要使用以下代码将其从Int转换为Byte:

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\u 3BYTE\u 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;
}

谢谢,我最终使用opencv的Mat格式工作,然后将其转换为BuffereImage以显示给用户,这需要很多重新工作的方法。但我会在有机会的时候试一试。
pOriginal
应该是
original
吗?@Sortofabeginner:是的,很准确。:-)谢谢现在编辑。