BufferImage和Mat互转

/**
 * BufferedImage转换成Mat
 *
 * @param original
 *            要转换的BufferedImage
 * @param imgType
 *            bufferedImage的类型 如 BufferedImage.TYPE_3BYTE_BGR
 * @param matType
 *            转换成mat的type 如 CvType.CV_8UC3
 */
public static Mat BufImg2Mat (BufferedImage original, int imgType, int matType) {
    if (original == null) {
        throw new IllegalArgumentException("original == null");
    }

    // Don't convert if it already has correct type
    if (original.getType() != imgType) {

        // Create a buffered image
        BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), imgType);

        // 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();
        }
    }

    byte[] pixels = ((DataBufferByte) original.getRaster().getDataBuffer()).getData();
    Mat mat = Mat.eye(original.getHeight(), original.getWidth(), matType);
    mat.put(0, 0, pixels);
    return mat;

}

//Mat转换为BufferedImage
public static BufferedImage matToBufferedImage(Mat mat)
{
    if (mat.height() > 0 && mat.width() > 0)
    {
        BufferedImage image = new BufferedImage(mat.width(), mat.height(),
                BufferedImage.TYPE_3BYTE_BGR);
        WritableRaster raster = image.getRaster();
        DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
        byte[] data = dataBuffer.getData();
        mat.get(0, 0, data);
        return image;
    }

    return null;
}

你可能感兴趣的:(java,opencv)