Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Proper(fast) way to extract pixel data from Mat in Java

Suspect I'm doing evil and want to know the right way.

I'm needing to copy a MAT of type CV_8UC3 into a Java BufferedImage. I was offered some code to do this, but it's taking excessive time - 34msec/frame for 640x480 image on my 8 core i7 The code (below) gets each pixel from the Mat via a get call. commenting out this line reduces conversion time to 3msec. Is there a way to get pixels in bigger batches? I'm new to OpenCV in Java, may be missing something simple.

condensing a bit

public static BufferedImage matToBufferedImage(Mat bgr) {
    int width = bgr.width();
    int height = bgr.height();
    BufferedImage image;
    WritableRaster raster;

        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        raster = image.getRaster();

        byte[] px = new byte[3];
        int[] rgb = new int[3];

        for (int y=0; y<height; y++) {

            for (int x=0; x<width; x++) {
                // this operation is really inefficient!
                bgr.get(y,x,px);
                rgb[0] = px[2];
                rgb[1] = px[1];
                rgb[2] = px[0];
                raster.setPixel(x,y,rgb);
            }
        }