Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

swing - Opencv java - Load image to 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
       .
       .
}

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.

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes there is more elegant way to do it. You can concert Mat to BufferedImage type and then just Load it with swing. The code to convert it to Buffered image is:

    Mat image_tmp = your image

    MatOfByte matOfByte = new MatOfByte();

    Highgui.imencode(".jpg", image_tmp, matOfByte); 

    byte[] byteArray = matOfByte.toArray();
    BufferedImage bufImage = null;

    try {

        InputStream in = new ByteArrayInputStream(byteArray);
        bufImage = ImageIO.read(in);
    } catch (Exception e) {
        e.printStackTrace();
    }

And then you just can paint it in your GUI object:

g.drawImage(bufImage , 0, 0, null);

where g is of type Graphics

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...