在 OpenCV 中将 `BufferedImage` 转换为 `Mat` [英] Converting `BufferedImage` to `Mat` in OpenCV
问题描述
如何将 BufferedImage
转换为 OpenCV
中的 Mat
?
How can I convert a BufferedImage
to a Mat
in OpenCV
?
我正在使用 OpenCV
的 JAVA 包装器(不是 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.Converted BufferedImage
到字节数组:
1.Converted BufferedImage
to byte array with:
byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
2.然后,如果您将 type 设置为 CV_8UC3
2. Then you can simply put it to Mat if you set type to CV_8UC3
image_final.put(0, 0, pixels);
您也可以尝试按照 这个答案
这篇关于在 OpenCV 中将 `BufferedImage` 转换为 `Mat`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!