Use OpenCV in your source code!

The recommended way of using OpenCV in your code is to use CMake with your code. If you are not using CMake with your code, the intructions below are not for you.

Solution

There are many ways to include OpenCV in your projects. I describe my way here which has the following advantages:

Setup your workstation:

Test your workstation by compiling a Hello World program

You probably know CMake by now, but I will provide a full hello world program here. You have to make two files: helloworld.cxx is your program code, and CMakeLists.txt defines your configuration for compilation.

helloworld.cxx looks like this:

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

int main ( int argc, char **argv )
{
  cvNamedWindow( "My 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( "My Window", img );
  cvWaitKey();
  return 0;
}

CMakeLists.txt looks like this:

PROJECT( helloworld_proj )
FIND_PACKAGE( OpenCV REQUIRED )
ADD_EXECUTABLE( helloworld helloworld.cxx )
TARGET_LINK_LIBRARIES( helloworld ${OpenCV_LIBS} )

It is assumed that you'll put the above two files (helloworld.cxx and CMakeLists.txt) in a folder. We will call this folder MYHOME/src/hw.

  1. Start CMake and choose your source folder to be MYHOME/src/helloworld
  2. Choose your build folder. I will choose MYHOME/build/helloworld
  3. Click Configure
  4. You will now have a variable called OpenCV_DIR. This variable is most likely pre-set to C:\OpenCV2.0.0 if you are on Windows. It may be undefined on other systems.
  5. Make sure you set the above variable to your BUILD folder of OpenCV, i.e. MYHOME/build/OpenCV. Since you built OpenCV with CMake, it remembers the path and all necessary stuff so that choosing the build folder will automatically pick up the necessary library path, include the correct include directory, set the correct list of library. In other words, the magic of CMake happens.
  6. Now you can click Generate to create the solution/makefile of your choice.
  7. Open this solution/makefile and build it.

If you get an executable helloworld program, you are ready to move on and have fun with OpenCV!

OpenCVWiki: Getting_started (last edited 2010-04-19 09:20:16 by Waldir)