0

What is the correct way to use Mat class in openCV (using java)

Mat Class ==> org.opencv.core.Mat and do I have to use BufferedImage when I want to read image into Mat. please show me Code answer

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.opencv.core.*;

public class opencv {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BufferedImage img1 = null, img2 = null;
        try {
            img1 = ImageIO.read(new File("c:\\test.jpg"));
          //  img1 = ImageIO.read(new File("c:\\Fig2.tif"));
           System.out.print(img1.getHeight());
        } catch (IOException e) {
        }

        //byte[] pxl1 = ((DataBufferByte) img1.getRaster()).getData();
        //Mat src1 = new Mat("");
        //Core.addWeighted(Mat1, alpha, Mat2, beta, gamma, dst);

    }

}

1 Answer 1

1

Assuming your image is 3 channel:

public Mat fromBufferedImage(BufferedImage img) {
    byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
    Mat mat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC3);
    mat.put(0, 0, pixels);
    return mat;
}

and the reverse:

public BufferedImage toBufferedImage(Mat mat) {
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (mat.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }
    byte[] bytes = new byte[mat.channels() * mat.cols() * mat.rows()];
    mat.get(0, 0, bytes);
    BufferedImage img = new BufferedImage(mat.cols(), mat.rows(), type);
    final byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
    System.arraycopy(bytes, 0, pixels, 0, bytes.length);
    return img;
}
Sign up to request clarification or add additional context in comments.

2 Comments

alright thx for explaining, do I have to use BufferedImage? this gives exception on .tif images how can i solve this
Probably the reason you see an exception is because the BufferedImage you are providing is null. ImageIO doesn't support TIFF without adding some libraries. See here: stackoverflow.com/questions/2898311/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.