在 OpenCV Java 中使用 Mat 显示图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26515981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display image using Mat in OpenCV Java
提问by pupilx
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? 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. I'll be grateful for any tips
我正在用 Java 用 OpenCV 编写我的第一个程序,我想问一下,是否可以仅使用 Mat 加载和显示文件中的图像?我在这个网站上找到了解决方案 http://answers.opencv.org/question/31505/how-load-and-display-images-with-java-using-opencv/但它之前将 Mat 更改为 Image 。我将不胜感激任何提示
采纳答案by guneykayim
回答by rafaoc
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/
回答by Milorenus Lomaliza
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 HighGuistatic object.
So you would first import it like:
这是一个老问题,但对于那些仍然面临同样问题的人来说,现在在 OpenCV for Java(我使用的是 4.1.1 版)的HighGui静态对象下实现了“imshow” 。
所以你首先要像这样导入它:
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 垫对象。