在OpenCV中将`BufferedImage`转换为`Mat` [英] Converting `BufferedImage` to `Mat` in OpenCV
问题描述
如何在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);
您也可以尝试像 查看全文