Monday, October 28, 2013

A Class That Converts OpenCV BGR to Java BufferedImage



package org.ski;
import java.awt.image.BufferedImage;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

public class Mat2Image {
    Mat mat = new Mat();
    BufferedImage img;
    byte[] dat;
    public Mat2Image() {}
    public Mat2Image(Mat mat) {
        getSpace(mat);
    }
    public void getSpace(Mat mat) {
        this.mat = mat;
        int w = mat.cols(), h = mat.rows();
        if (dat == null || dat.length != w * h * 3)
            dat = new byte[w * h * 3];
        if (img == null || img.getWidth() != w ||
                           img.getHeight() != h)
            img = new BufferedImage(w, h,
                    BufferedImage.TYPE_3BYTE_BGR);
    }
    BufferedImage getImage(Mat mat){
        getSpace(mat);
        mat.get(0, 0, dat);
        img.getRaster().setDataElements(0, 0,
               img.getWidth(), img.getHeight(), dat);
        return img;
    }
    static{
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }
}

1 comment:

  1. This generates image with incorrect color plane. You need to use something like:

    /**
    * Convert from Mat to BufferedImage.
    *
    * @param mat
    * Mat array.
    */
    public static BufferedImage convert(final Mat mat) {
    final Mat mat2 = new Mat();
    BufferedImage bufferedImage = null;
    byte[] pixelBytes = null;
    int type = BufferedImage.TYPE_BYTE_GRAY;
    // Color image
    if (mat.channels() > 1) {
    Imgproc.cvtColor(mat, mat2, Imgproc.COLOR_BGR2RGB);
    type = BufferedImage.TYPE_3BYTE_BGR;
    }
    final int pixels = mat.channels() * mat.cols() * mat.rows();
    // Create byte array if null or different length
    if (pixelBytes == null || pixelBytes.length != pixels) {
    pixelBytes = new byte[pixels];
    }
    mat2.get(0, 0, pixelBytes);
    bufferedImage = new BufferedImage(mat.cols(), mat.rows(), type);
    bufferedImage.getRaster().setDataElements(0, 0, mat.cols(), mat.rows(),
    pixelBytes);
    return bufferedImage;
    }

    ReplyDelete