Thursday, October 17, 2013

Install OpenCV 2.6.4 on Ubuntu 12.04

I can still remember the time I was installing OpenCV library three years ago. It's not easy for the first time to install such a large library onto my own IDE. Knowledges about "Makefiles", system PATH, pkg-config, etc. are required to setup OpenCV. Also, you may also be familiar with your IDF, so that you can find where to fill in the right settings.

Here, take a common environment as example, is the way to install OpenCV 2.6.4 (or any other latest version) on Ubuntu 12.04. This is simple thanks for the script written by jayrambhia.


  1. git clone https://github.com/jayrambhia/Install-OpenCV
  2. cd Install-OpenCV/Ubuntu
  3. chmod +x opencv_latest.sh
  4. ./opencv_latest.sh

These steps ask the machine to download the script from jayrambhia's github, then run the script in it. Remember you may be asked to type in your password in order to run the "sudo" commands. After running the four commands, you'll completely installed OpenCV on your Ubuntu machine.

Then, it's time to run a hello world program. Create a new directory (mkdir), and create a new cpp code (let's say main.cpp here).

In main.cpp:
#include <cv.h>
#include <highgui.h>
int main ( int argc, char **argv )
{
    cvNamedWindow( "Hello Window", 1 );
    IplImage *img = cvCreateImage( cvSize( 640, 480 ), IPL_DEPTH_8U, 1 );

    CvFont font;
    double hScale = 1.0;
    double vScale = 1.0;
    int lineWidth = 1;

    cvInitFont( &font, CV_FONT_HERSHEY_SIMPLEX | CV_FONT_ITALIC,
            hScale, vScale, 0, lineWidth );
    cvPutText( img, "Hello World!", cvPoint( 200, 400 ), &font,
            cvScalar( 255, 255, 0 ) );

    cvShowImage( "Hello Window", img );
    cvSaveImage("out.jpg", img, 0);
    cvWaitKey();

    return 0;
}

After save and quit, run command as below to compile:
g++ main.cpp -o main `pkg-config --cflags --libs opencv`
You will get a executable file called "main", and that the one you want. Run it by this command:
./main
It's all done;however, to save time, we can create a file  called "Makefile" with the following content:
CFLAGS = `pkg-config --cflags opencv`
LIBS = `pkg-config --libs opencv`

main : main.cpp
    g++ -o $@ $< $(CFLAGS) $(LIBS)
Then you can simply type this instead of calling g++ directly.
make

Reference: https://github.com/jayrambhia/Install-OpenCV/tree/master/Ubuntu

No comments:

Post a Comment