Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image using Mat in OpenCV Java

Tags:

java

opencv

mat

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

like image 616
pupilx Avatar asked Dec 20 '22 10:12

pupilx


2 Answers

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.
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.

like image 54
Milorenus Lomaliza Avatar answered Jan 02 '23 10:01

Milorenus Lomaliza


You can use the next code to transform a cvMat element into a java element: BufferedImage or 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/

like image 29
rafaoc Avatar answered Jan 02 '23 11:01

rafaoc