Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

java - Converting `BufferedImage` to `Mat` in OpenCV

How can I convert a BufferedImage to a Mat in OpenCV?

I'm using the JAVA wrapper for OpenCV(not JavaCV). As I am new to OpenCV I have some problems understanding how Mat works.

I want to do something like this. (Based on Ted W. reply):

BufferedImage image = ImageIO.read(b.getClass().getResource("Lena.png"));

int rows = image.getWidth();
int cols = image.getHeight();
int type = CvType.CV_16UC1;
Mat newMat = new Mat(rows, cols, type);

for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
        newMat.put(r, c, image.getRGB(r, c));
    }
}

Highgui.imwrite("Lena_copy.png", newMat);

This doesn't work. Lena_copy.png is just a black picture with the correct dimensions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I also was trying to do the same thing, because of need to combining image processed with two libraries. And what I’ve tried to do is to put byte[] in to Mat instead of RGB value. And it worked! So what I did was:

1.Converted BufferedImage to byte array with:

byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

2. Then you can simply put it to Mat if you set type to CV_8UC3

image_final.put(0, 0, pixels);

Edit: Also you can try to do the inverse as on this answer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...