Friday, November 4, 2011

Installing OpenCV in Ubuntu with Eclipse

For some reason I had a lot of trouble installing OpenCV on a Linux system, so here's hoping this will help someone.
Although building from source offers a greater level of customization, this tutorial will not go into that for various reasons.

This was tested in Ubuntu 11.10, but it should work on older versions and/or Ubuntu derivatives (like Linux Mint, Bodhi Linux etc.) as well.
First and foremost, we will install OpenCV then move on to installing Eclipse and lastly make them work together.

Become root and enter these commands.
add-apt-repository ppa:gijzelaar/opencv2.3
apt-get update
apt-get install libopencv-dev

If there were no errors, OpenCV 2.3 should be now installed. Install Eclipse either from the repository or from their official site.

Open up Eclipse and create new C++ project. Once the project is made, right click on it and go to properties.
Select C/C++ Build from the menu on the left, then select the Settings entry from the submenu. Go to the first tab, Tool Settings and under GCC C++ Compiler select Includes (or Directories) and add the path
/usr/include/opencv
.
Adding include path
Now go to Libraries under GCC C++ Linker, and add the libraries that you need. The following libraries can be added:
opencv_core
opencv_imgproc
opencv_highgui
opencv_ml
opencv_video
opencv_features2d
opencv_calib3d
opencv_objdetect
opencv_contrib
opencv_legacy
opencv_flann

The most basic libraries are opencv_core and opencv_highgui, be sure to always add these. Under the Library search path add
/usr/lib
.
Do add these paths and libraries for both the Debug and Release builds of your project.
Adding libraries to project
Click OK to continue.
Copy an image in to your project folder, name it image.jpg then create a new main.cpp file and insert the following test code.
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cv.h>
#include <highgui.h>

int main(int argc, char *argv[])
{
IplImage* img = 0;

img=cvLoadImage("image.jpg");

cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);

cvShowImage("mainWin", img );

cvWaitKey(0);

cvReleaseImage(&img );

system("PAUSE");
return 0;
}


Build and run the project, and if you set up everything correctly, you should see a window pop up with your image inside it.
If you get compile errors reread this post and make sure you set up the includes and libraries correctly.