Ask Your Question
1

How load and display images with java using opencv [SOLVED]

asked 2014-04-09 20:10:15 -0500

rafaoc gravatar image

updated 2014-11-26 23:57:16 -0500

I am working with java usign opencv. Basically I want to read and display an image using opencv functions. I wanted to translate the next code from c++ to java but i dont find the same opencv functions for java.


include "opencv2/highgui/highgui.hpp"
include "iostream"
using namespace cv;
using namespace std;
int main(){
Mat img = imread("lena.png", CV_LOAD_IMAGE_COLOR);
    if (img.empty()){
    cout << "Cannot load image!" << endl;
    return -1;
    }
namedWindow("image", CV_WINDOW_AUTOSIZE);
imshow("image", img);
waitKey(0);
return 0;
}
 
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
4

answered 2014-04-24 23:30:26 -0500

rafaoc gravatar image

I have done it !

You can use the next code to transform a cvMat element into a java element: BufferedImage or Image:

    public BufferedImage Mat2BufferedImage(Mat m){
// source: http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/
// Fastest code
// The 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);

}
edit flag offensive delete link more

Comments

Do accept your solutions as an answer, so that the topic shows solved! Thanks for the response.

StevenPuttemans gravatar imageStevenPuttemans ( 2014-04-25 03:26:17 -0500 )edit
Login/Signup to Answer

Question Tools

Stats

Asked: 2014-04-09 20:10:15 -0500

Seen: 27,283 times

Last updated: Nov 26 '14