OpenCV Java-将图像加载到GUI [英] Opencv java - Load image to GUI

查看:110
本文介绍了OpenCV Java-将图像加载到GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java Opencv-2.4.4和swing GUI开发应用程序.问题是我找不到任何解决方案,该解决方案显示了如何将处理后的图像(保存在 Mat 对象中)打印到java swing GUI的有效方法.目前,我正在使用这种笨拙的解决方案:

I'm developing an application using Java Opencv-2.4.4 and swing GUI. Problem is that I'm unable to find any solution, that shows efficient way how to print processed image (saved in Mat object) to java swing GUI. For this moment I'm using this clumsy solution:

javax.swing.JLabel outputImage;
outputImage.setIcon(new javax.swing.ImageIcon("/home/username/Output.png"));

private void sliderStateChanged(javax.swing.event.ChangeEvent evt) { 
       .
       .
  Mat canny; // Here is saved what I want to plot
  String filename = "/home/username/Output.png";
  Highgui.imwrite(filename, canny);  // write to disk
  outputImage.setIcon(new ImageIcon(ImageIO.read(new File(filename)))); //update Icon
       .
       .
}

当用户更改某些值,输入等时,在GUI中,我必须覆盖磁盘上的 Output.png 并用磁盘上的新映像更新jLabel.

When user changes some values, inputs etc ., in GUI I have to overwrite Output.png on disk and update jLabel with new image from disk.

有没有更优雅/有效的解决方案呢?是否可以将 Mat 对象直接绘制或转换为 Canvas Image 或将任何可打印为图像的东西转换为图像?

Is there any more elegant / efficient solution to this ? Is it posible to plot or convert Mat object directly to Canvas or Image or anything that is printable as image in swing ?

推荐答案

jpeg编码很有趣,但是有两个问题:

jpeg encoding is interesting, but there are a couple problems:

  • 这不是一种无损格式,压缩时您将丢失图像数据
  • 需要一段时间(比下面建议的时间长6至10倍)
public Image toBufferedImage(Mat m){
      int type = BufferedImage.TYPE_BYTE_GRAY;
      if ( m.channels() > 1 ) {
          type = BufferedImage.TYPE_3BYTE_BGR;
      }
      int bufferSize = m.channels()*m.cols()*m.rows();
      byte [] b = new byte[bufferSize];
      m.get(0,0,b); // get all the pixels
      BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
      final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
      System.arraycopy(b, 0, targetPixels, 0, b.length);  
      return image;

  }

这篇关于OpenCV Java-将图像加载到GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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