1) Install opencv. Refer http://opencv.willowgarage.com/wiki/InstallGuide. After installing a directory will be created. In my installation it is C:\OpenCV2.1.
2) Start VS2008. Go to File->new->project. Select Visual C++->Win32->Win32 Console Application.
3) Give a name. Click next and then finish. A new project will be created.
4) Go to Project->
5) In ‘Property’ dialog go to Config properties->c/c++. In ‘Additional Directories’ option add directory of opencv include files.( C:\OpenCV2.1\include\opencv)
6) Again in same dialog go to Config properties->Linker->General. In ‘Additional Libraries’ option add directory of opencv libraries.( C:\OpenCV2.1\lib)
7) Go to Config properties->Linker->Input. In ‘Additional Dependacies’ option add files ‘cv210d.lib’ ‘highgui210.lib’. These files are library files for respective header files. In this example we are using two header files ‘cv.h’ and ‘highgui.h’.
Now you are set with all requirements. So get ready to start with your first opencv program. In this example we are going to show feed from a video camera.
You will need a camera attached to your computer. It will act as image source. You can use a video file also. Opencv has data structure ‘CvCapture’ representing this image source. Opencv has built in function to create ‘CvCapture’ from camera. Its prototype is
CvCapture * cvCreateCameraCapture(int index)
‘index’ is index of camera. Use -1 for default.
Another data structure is ‘IplImage’. It represents an image.
Following lines captures an image from camera.
CvCapture *c=cvCreateCameraCapture(-1);
IplImage *frame;
frame=cvQueryFrame(c);
cvReleaseCapture( &capture );
‘cvQueryFrame’ function retrieves an image from ‘CvCapture’ and returns an ‘IplImage’. Memory of capture is released by ‘CvReleaseCapture’ function.
To show the captured image we need a user interface. Opencv has provided windows library in ‘highgui.h’ file. Following are basic functions of windows
int cvNamedWindow(const char * name, int flag=1)
It creates a new window with ‘name’.
void cvShowImage(const char * name, const CvArr * image)
It displays image in window named ‘name’. If window is not already created using ‘cvNamedWindow’ function, it creates a window.
void cvDestroyWindow( const char * name)
Using above functions we can write our first program.
#include "cv.h"
#include "highgui.h"
int main(int argc, char* argv[])
{
CvCapture *c=cvCreateCameraCapture(-1);
IplImage *frame;
while(true)
{
frame=cvQueryFrame(c);
cvShowImage("Window",frame);
char ch=cvWaitKey(15);
if(ch==27)
break;
}
return 0;
}
Here we have used ‘cvWaitkey’. It waits 15 msec for any key press. If a key is pressed it returns its ASCII else returns 0. We then compare it with ASCII value of ‘Esc’ and break the while loop. This delay is important otherwise the program will stuck in infinite loop and nothing will be displayed in window.
Cross your fingers and press F5. If you are lucky your program will run without error.