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

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

问题描述

如何在OpenCV中将BufferedImage转换为Mat?
我使用java包装器进行OpenCV(而不是JavaCV)。由于我是OpenCV的新手,我在理解Mat的工作原理时遇到了一些问题。

How can I convert a BufferedImage to a Mat in OpenCV? Im 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);

修改:
另外你可以尝试做反向与相同这个答案

这篇关于在opencv中将BufferedImage转换为Mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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