2013년 6월 16일 일요일

Converting Java BufferedImage to OpenCV Mat and vice versa

BufferedImage to Mat

BufferedImage image = myBufferedImage;
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
Mat mat = new Mat(image.getHeight(), image.getWidth, CvType.CV_8UC3);
mat.put(0, 0, data);


Mat to BufferedImage

Mat mat = myMat;
byte[] data = new byte[mat.rows()*mat.cols()*(int)(mat.elemSize())];
mat.get(0, 0, data);
if (mat.channels() == 3) {
for (int i = 0; i < data.length; i += 3) {
byte temp = data[i];
data[i] = data[i + 2];
data[i + 2] = temp;
}
}
BufferedImage image = new BufferedImage(mat.cols(), mat.rows(), BufferedImage.TYPE_3BYTE_BGR);
image.getRaster().setDataElements(0, 0, mat.cols(), mat.rows(), data);

댓글 4개:

  1. My God! Took me forever to find this, which was similar to something else I found before here...
    http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/
    Thanks a lot!!

    답글삭제
  2. I am getting
    Exception in thread "main" java.lang.ClassCastException: java.awt.image.DataBufferInt cannot be cast to java.awt.image.DataBufferByte at line
    DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
    Kindly help!!!

    답글삭제
    답글
    1. If the data type of the instance of BufferedImage is integer type, you should use DataBufferInt to get data buffer. You can check the data type of the BufferedImage by using the function getType().

      삭제