Installing Java OpenCV in Eclipse for Windows 7

This one is a bit easier, since the official guide from OpenCV is accurate and I’ve followed it without any trouble. So, you just need to do these:

  1. Download and install JDK
  2. Download and install eclipse
  3. Follow this guide from OpenCV’s website

As for testing, you can use the following code, who will do the exact same thing as in the C++ version. You may note that this code is longer than its C++ counterpart. That’s because Java OpenCV doesn’t have equivalent method for imshow() in C++. So, most of the code here are doing image conversion from Mat data type to something that Java can display.

import java.awt.*;						// for ImageIcon type
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import javax.swing.*; 					// for ImageIcon type
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;

// This class displays image 
// Its first function converts from Mat to BufferedImage
// Second function displays the converted image
class ImageDisplayer
   public BufferedImage Mat2BufferedImage(Mat m)
		//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;	
   public void displayImage(Image img2)
	   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();

// This is the main class
// We load image using OpenCV as a Mat
public class hello
	public static void main( String[] args )
	    System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
		Mat img = Highgui.imread("C:\\Users\\Didit\\Pictures\\fifa.png"); //Change to any file you want
	    ImageDisplayer displayer = new ImageDisplayer();
		Image imgToShow = displayer.Mat2BufferedImage(img);

I didn’t actually notice that there would be so much code in the beginning, but Java is pretty easy to read anyway. So, I don’t think this trade off should scare you from using OpenCV in Java.


  1. […] forrásokat), amik egész szimpatikusak lettek: Enthought (Python + OpenCV), JavaCV (Java + OpenCV). MS Visual Studio-hoz pedig nagyszerű kiegészítés a VisualMicro, hogy ne kelljen az Arduino […]


Leave a Reply