OpenCV输出在Jpanel中使用Mat对象 [英] OpenCV output Using Mat object in Jpanel

查看:230
本文介绍了OpenCV输出在Jpanel中使用Mat对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以使用以下代码使用Jpanel输出图像:

I know we can output an Image using Jpanel using the following code:

   JFrame frame = new JFrame("IMG");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   frame.setResizable(true);
   frame.setLocationRelativeTo(null);

   ImageIcon image = new ImageIcon(".../img.jpg");
   frame.setSize(image.getIconWidth()+10,image.getIconHeight()+35);

   JLabel label1 = new JLabel(" ", image, JLabel.CENTER);
   frame.getContentPane().add(label1);

   frame.validate();
   frame.setVisible(true);

此代码假定我已在目录中创建或已有图像文件。但我想要做的是直接在Jpanel中输出图像而不创建图像文件。如何在JAVA中使用OpenCV Mat对象?

This code would assume that I have created or already have an image file in my directory. But what I want to do is output the image in the Jpanel directly without creating the image file. How do I do that using OpenCV Mat object in JAVA?

推荐答案

您可以转换 Mat 使用以下方法对象 BufferedImage 对象:

You can convert Mat object to BufferedImage object using following method:

public static BufferedImage createAwtImage(Mat mat) {

    int type = 0;
    if (mat.channels() == 1) {
        type = BufferedImage.TYPE_BYTE_GRAY;
    } else if (mat.channels() == 3) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    } else {
        return null;
    }

    BufferedImage image = new BufferedImage(mat.width(), mat.height(), type);
    WritableRaster raster = image.getRaster();
    DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
    byte[] data = dataBuffer.getData();
    mat.get(0, 0, data);

    return image;
}

然后你可以使用 ImageIcon

// Load image using Highgui or create Mat object other way you want
Mat mat = Highgui.imread(".../img.jpg");

ImageIcon image = new ImageIcon(createAwtImage(mat));

这篇关于OpenCV输出在Jpanel中使用Mat对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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