Converting BufferedImage to Mat (OpenCV) in Java [duplicate]

核能气质少年 提交于 2019-12-01 00:45:48

You can try this method, to actually convert the image to TYPE_3BYTE_BGR (your code simply created a blank image of the same size, that is why it was all black).

Usage:

// Convert any type of image to 3BYTE_BGR
im = toBufferedImageOfType(im, BufferedImage.TYPE_3BYTE_BGR);

// Access pixels as in original code

And the conversion method:

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!