简体   繁体   English

在 OpenCV Java 中使用 Mat 显示图像

[英]Display image using Mat in OpenCV Java

I am writing my first program in OpenCV in Java and I'd like to ask, is it possible to load and display image from file only using Mat?我正在用 Java 用 OpenCV 编写我的第一个程序,我想问一下,是否可以仅使用 Mat 加载和显示文件中的图像? I found solution on this website http://answers.opencv.org/question/31505/how-load-and-display-images-with-java-using-opencv/ but it changes Mat to Image before.我在这个网站上找到了解决方案http://answers.opencv.org/question/31505/how-load-and-display-images-with-java-using-opencv/但它之前将 Mat 更改为 Image 。 I'll be grateful for any tips我将不胜感激任何提示

This is an old question but for those who still face the same problem there is an implementation of "imshow" now in OpenCV for Java (I am using verion 4.1.1) under HighGui static object.这是一个老问题,但对于那些仍然面临同样问题的人来说,现在在 OpenCV for Java(我使用的是 4.1.1 版)的HighGui静态对象下实现了“imshow”。
So you would first import it like:所以你首先要像这样导入它:

import org.opencv.highgui.HighGui;

and then display the image like:然后显示图像,如:

HighGui.imshow("Image", frame);
HighGui.waitKey();

Where 'frame' is your OpenCV mat object.其中“框架”是您的 OpenCV 垫对象。

You can use the next code to transform a cvMat element into a java element: BufferedImage or Image:您可以使用以下代码将 cvMat 元素转换为 java 元素:BufferedImage 或 Image:

 public BufferedImage Mat2BufferedImage(Mat m) {
    // Fastest code
    // output can be assigned either to a BufferedImage or to an Image

    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;
}

And then display it with:然后显示它:

public void displayImage(Image img2) {

    //BufferedImage img=ImageIO.read(new File("/HelloOpenCV/lena.png"));
    ImageIcon icon=new ImageIcon(img2);
    JFrame frame=new JFrame();
    frame.setLayout(new FlowLayout());        
    frame.setSize(img2.getWidth(null)+50, img2.getHeight(null)+50);     
    JLabel lbl=new JLabel();
    lbl.setIcon(icon);
    frame.add(lbl);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

source: http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/来源: http : //answers.opencv.org/question/10344/opencv-java-load-image-to-gui/

Nope, there is no imshow equivalent in java.不,java 中没有imshow等效项。 Please refer this link.请参考这个链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM