在OpenCV中将`BufferedImage`转换为`Mat` [英] Converting `BufferedImage` to `Mat` in OpenCV

查看:103
本文介绍了在OpenCV中将`BufferedImage`转换为`Mat`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在OpenCV中将BufferedImage转换为Mat?

我正在将Java包装器用于OpenCV(不是 JavaCV ).由于我是OpenCV的新手,因此在理解Mat的工作方式时遇到了一些问题.

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

我想做这样的事情. (基于Ted W.的回复):

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);

这不起作用. Lena_copy.png只是尺寸正确的黑色图片.

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

推荐答案

我还试图做同样的事情,因为需要将经过处理的图像与两个库结合在一起.我尝试做的是将byte[]放入Mat而不是RGB值.而且有效!所以我所做的是:

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.将BufferedImage转换为字节数组:

1.Converted BufferedImage to byte array with:

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

2.然后,如果您将类型设置为 CV_8UC3

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

image_final.put(0, 0, pixels);

您也可以尝试像 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆