DCPrime's
Blog

OpenCV: Basics

Published on 23 Aug 2013

OpenCV as you all know is an open-source Computer Vision library for C, C++ and also Python. This post will guide you for how to use and how to implement any problem on OpenCV. First of all an apology for not writing any post till now. From last week I am thinking about the topic to write for the blog and I came up with this. Choose any one from the given two Integrated Development Environments(IDEs) its needed for developing a project then even executable file at the end and it also helps a lot in debugging.

Eclipse IDE:

As we are dealing with C and C++  we need an environment for developing the program so we use Eclipse (here). Precisely Eclipse’s CDT plugin. You need to download it from here. Its around 100 MBs.

Visual Studio:

For detailed instructions on configuring OpenCV on Visual Studio and Eclipse Please visit OpenCV on VS and OpenCV on Eclipse respectively.

Basics:

Basics of OpenCV also starts with reading an image and showing it in a window. Well its not as simple as it was in Matlab. So before reading an image lets start with the basic structure of OpenCV C language program.

#include "stdafx.h" //if you are using Visual Studio
#include <cv.h>
int main()
{
declaration of variables;
\...
program;
\...
return 0;
}

For C++:

#include <cv.h>using namespace cv;int main()
{
\...
return 0;
}

For Python:

from cv2.cv import *
\...
\...

The function in OpenCV header file cv.h for reading an image is cvLoadImage() in C and imread() in C++. From that you may get an idea C++ is better to code in rather than C (later you will think its better to code in Python* rather than C++) Following is the code for reading an image and displaying on a window named “Display”

#include<cv.h>
#include<highgui.h>
int main()
{
IplImage* img1 = cvLoadImage("C:\image\path", CV_LOAD_IMAGE_COLOR);
	cvNamedWindow("Display", CV_WINDOW_AUTOSIZE);
	cvShowImage("Display",img1);
	cvWaitKey(0);
	cvReleaseImage(&img1);
	return 0;
}

Explanation

Starting from the beginning “The Header Files”

Now “The Code”

Well that ended the C part now almost the same remains in both C++ and Python. The codes are given with comments in the and they are self-explanatory .

For C++:

#include <cv.h>
#include <highgui.h>
using namespace cv;
int main()
{
	Mat image;  //Image is in form of matrix (here)
	image = imread("/home/darshil/images/hello.jpg", 1 );
	if(!image.data ) //Check if image has data
	{
		printf( "No image data \n" );
		return -1;
	}
	namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
	imshow( "Display Image", image );
	waitKey(0);
	return 0;
}

For Python:

from cv2.cv import * # importing the opencv module
img=LoadImageM("path/to/image.jpg") # loading image in form of matrix 
NamedWindow("Display",CV_WINDOW_AUTOSIZE) # Creating a window
ShowImage("Display",img)  #Displaying the image
WaitKey(0) #waitkey to wait till the output comes

This is it.

End of Post.