Ask Your Question

imshow equivalence in Java

asked 2013-05-02 07:43:34 -0500

phamnamlong gravatar image

updated 2013-05-02 07:44:32 -0500

How do you do imshow in the Java binding of OpenCv ? I cannot find any reference of it in Highgui. The example below shows the use of imshow as in C++. I would like to ask for the equivalence in Java.

#include <cv.h>
#include <highgui.h>

using namespace cv;

int main( int argc, char** argv){
 char* imageName = argv[1];
 Mat image;
 image = imread( imageName, 1 );

 if( argc != 2 || ! ) {
   printf( " No image data \n " );
   return -1;
 namedWindow( imageName, CV_WINDOW_AUTOSIZE );
 imshow( imageName, image );
 return 0;
edit retag flag offensive close merge delete

2 answers

Sort by » oldest newest most voted

answered 2013-09-23 05:08:18 -0500

Arne gravatar image

updated 2013-09-23 05:08:47 -0500

It seems that there isn't a function like imshow in the Java HighGUI package. But after a small search i found out that its possible to encode the image to a "BufferedImage" and then just load it into your GUI. So just load it like this:

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 =;
} catch (Exception e) {

and then draw it like that:

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

g in this examples is an instance of the class Graphics

Hopefully this is what you were searching for.

edit flag offensive delete link more


Is it required to compress the image to jpg for uploading it into the component? Couldn't we just use Mat.get and copy the uncompressed byte array?

Jose Gómez gravatar imageJose Gómez ( 2013-11-09 12:13:37 -0500 )edit

You don't need to compress it to .jpg. You can do it like this:

public Image toBufferedImage(Mat m){
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if ( m.channels() &gt; 1 ) {
        Mat m2 = new Mat();
        type = BufferedImage.TYPE_3BYTE_BGR;
        m = m2;
    byte [] b = new byte[m.channels()*m.cols()*m.rows()];
    m.get(0,0,b); // get all the pixels
    BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
    image.getRaster().setDataElements(0, 0, m.cols(),m.rows(), b);
    return image;


Best regards,

Daniel Baggio gravatar imageDaniel Baggio ( 2013-12-30 04:14:39 -0500 )edit

answered 2014-02-18 15:43:47 -0500

Atul gravatar image

This is a readymade solution for Imshow() equivalent in Java OpenCV Its simple to use . API will look like:

Imshow im = new Imshow("Title");


Visit here

edit flag offensive delete link more


This does not work anymore since highgui is deprecated.

frageDE gravatar imagefrageDE ( 2016-04-07 11:04:28 -0500 )edit

Question Tools


Asked: 2013-05-02 07:43:34 -0500

Seen: 9,355 times

Last updated: Feb 18 '14