opencv Using Cascade Classifiers In Java Converting an Mat object to an BufferedImage object


Example

This example by Daniel Baggio was taken directly from this StackExchange answer, but has been reposted for visibility.

This class takes an Mat object and returns the BufferedImage object used by the javax.swing libraries. This can be used by a Graphics object to draw the image.

private BufferedImage toBufferedImage(Mat m) {
    if (!m.empty()) {
        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (m.channels() > 1) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        int bufferSize = m.channels() * m.cols() * m.rows();
        byte[] b = new byte[bufferSize];
        m.get(0, 0, b); // get all the pixels
        BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
        final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        System.arraycopy(b, 0, targetPixels, 0, b.length);
        return image;
    }
    
    return null;
}