Professional Documents
Culture Documents
Key Features
Optimized for real time image processing & computer
vision applications
Primary interface of OpenCV is in C++
There are also C, Python and JAVA full interfaces
OpenCV applications run on Windows, Android, Linux,
Mac and iOS
Optimized for Intel processors
OpenCV Modules
imgproc
This module includes basic image processing algorithms
including image filtering, image transformations, color space
conversions and etc.
video
This is a video analysis module which includes object tracking
algorithms, background subtraction algorithms and etc.
objdetect
This includes object detection and recognition algorithms for
standard objects.
Header files
These are some of important OpenCV header files for C++ interface.
As a beginner, you will need few of these header files for your
application. In my following lessons, I will include only necessary
header files to my example programs. If you are not sure what to
include, include them all. No any penalty incurred for including all
this header file except for a fact that the length of your source code
will increased by few lines than necessary.
o #include "opencv2/core/core.hpp"
o #include "opencv2/flann/miniflann.hpp"
o #include "opencv2/imgproc/imgproc.hpp"
o #include "opencv2/photo/photo.hpp"
o #include "opencv2/video/video.hpp"
o #include "opencv2/features2d/features2d.hpp"
o #include "opencv2/objdetect/objdetect.hpp"
o #include "opencv2/calib3d/calib3d.hpp"
o #include "opencv2/ml/ml.hpp"
o #include "opencv2/highgui/highgui.hpp"
o #include "opencv2/contrib/contrib.hpp"
o #include "opencv2/core/core_c.h"
o #include "opencv2/highgui/highgui_c.h"
o #include "opencv2/imgproc/imgproc_c.h"
Namespace
All OpenCV classes and functions are in cv namespace. So, you have
to do one of following
Add the 'using namespace cv' line just after including your
header files (I have used this method in all my sample programs)
e.g.
#include "opencv2/core/core.hpp"
using namespace cv;
int main()
{
Mat frame = cvQueryFrame(
capture );
imshow( "Video", frame );
}
int main()
{
cv::Mat frame = cvQueryFrame(
capture );
cv::imshow( "Video", frame );
}
Data type of an array defines the number of bits allocated for each
element of array (pixels in an image) and how the value is represented
using those bits. Any array elements should have one of following
data types.
We can define all of above data types for multi channel arrays
(supports up to 512 channels). Here I am going to show you
how to define CV_8U data type for multi channel arrays.
CV_8UC1 (single channel array with 8 bit unsigned
integers)
CV_8UC2 (2 channel array with 8 bit unsigned integers)
CV_8UC3 (3 channel array with 8 bit unsigned integers)
CV_8UC4 (4 channel array with 8 bit unsigned integers)
CV_8UC(n) (n channel array with 8 bit unsigned integers
(n can be from 1 to 512) )
e.g. 1 : Here I have illustrated a 3 channel array with 8 bit
unsigned integers. As the datatype is 8 bit unsigned integers,
each element should have a value from 0 to 255. Because this
is a 3 channel array, array consists of tuples with 3 elements.
The first tuple is {54, 0, 34}, second tuple is {58, 78, 185} and
so on.
3 Channel Arrays
2 Channel Array
Note : CV_8U = CV_8UC1 = CV_8UC(1)
Example Usage :
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
namedWindow("MyWindow",
CV_WINDOW_AUTOSIZE); //create a window with the name
"MyWindow"
imshow("MyWindow", img); //display the image which is
stored in the 'img' in the "MyWindow" window
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////
Before you run this program, put any image file (MyPic.JPG) into the
folder where your c++ file is.Otherwise you have to change the first
argument of imread() function and give the absolute path to your
image file.
You can download this OpenCV visual c++ project from here. (The
downloaded file is a compressed .rar folder. So, you have to extract it
using Winrar or other suitable software)
#include "opencv2/highgui/highgui.hpp"
imread(), namedWindow(), imshow() and waitKey() functions
are declared in the above header file. So you must include it.
In the above model, top left pixel is (23, 231, 46). It will be
shown as a greenish color because the green value(231) of
that pixel is larger than the red(23) and blue(46) value.
if (img.empty())
If imread() function fails to load the image, 'img' will not be
loaded any data. Therefore 'img.empty()' should return true.
It's a good practice to check whether the image is loaded
successfully and if not exit the program. Otherwise your
program will crash when executing imshow()function.
bool Mat::empty()
This function returns true, if Mat::data==NULL or Mat::total() == 0
//system("pause");
If you are using Visual Studio, it's better to uncomment this line
because it will pause the program until user press any key. If
we don't uncomment it, the program will exit immediately so
that user will not see the error message.
void namedWindow(const string& winname, int flags
= WINDOW_AUTOSIZE);
This function creates a window.
Parameters -
o winname - Title of the window. That name will
display in the title bar of the newly created window
o flags - determine the size of the window. There are
two options
WINDOW_AUTOSIZE - User cannot resize the
image. Image will be displayed in its original size
CV_WINDOW_NORMAL - Image will resized if
you resize the the window
Parameters -
o winname - Title of the window. This name is used to
identify the window created by namedWindow() function.
o mat - hold the image data
Summary
namedWindow("MyWindow",
CV_WINDOW_AUTOSIZE); //create a window with the name
"MyWindow"
imshow("MyWindow", img); //display the image which is
stored in the 'img' in the "MyWindow" window
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////
Before you run this program, put any image file (MyPic.JPG) into the
folder where your c++ file is.Otherwise you have to change the first
argument of imread() function and give the absolute path to your
image file.
You can download this OpenCV visual c++ project from here. (The
downloaded file is a compressed .rar folder. So, you have to extract it
using Winrar or other suitable software)
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //c
reate a window called "MyVideo"
while(1)
{
Mat frame;
return 0;
New OpenCV functions which are not found earlier are explained
here
VideoCapture::VideoCapture(int device)
This is one of constructors available in VideoCapture class. This
constructor open the camera indexed by the argument of this
constructor and initializes the VideoCapture object for reading
the video stream from the specified camera.
Here the '0' means the index of the camera to be used. You can use
1,2,3.. instead of 0, if your computer is attached to more than 1 camera.
The destructor of this class will deallocated any associated memory
with this object. Therefore you don't need to deallocate memory
explicitly in your program.
if (!cap.isOpened())
If the VideoCapture object initialization unsuccessful, the
expression inside the 'if 'parentheses will evaluate to true and the
statements inside the 'if' block will be executed.
It is a good practice to check this scenario and handle it
accordingly because otherwise it may cause the program to
crash.
double dWidth =
cap.get(CV_CAP_PROP_FRAME_WIDTH)
This function obtain the width (in pixels) of frames of the camera
output.
double dHeight =
cap.get(CV_CAP_PROP_FRAME_HEIGHT)
This function obtain the height (in pixels) of frames of the camera
output.
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
compression_params.push_back(CV_IMWRITE_JPEG_QUA
LITY); //specify the compression technique
compression_params.push_back(98); //specify
the compression quality
if ( !bSuccess )
}
namedWindow("MyWindow",
CV_WINDOW_AUTOSIZE); //create a window with the name
"MyWindow"
imshow("MyWindow", img); //display the image which is
stored in the 'img' in the "MyWindow" window
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////
You can download this OpenCV visual c++ project from here. (The
downloaded file is a compressed .rar folder. So, you have to extract it
using Winrar or other suitable software)
The above program is very much similar to the program under 'Create
a Blank Image & Display' section in the lesson of Read & Display
Image. If you need further clarifications of any OpenCV functions
which are not explained here, please refer to Read & Display
Image lesson.
Parameters -
The image format is chosen depending on the file name extension. Only
images with 8 bit or 16 bit unsigned single channel or 3 channel (
CV_8UC1, CV_8UC3, CV_8SC1, CV_8SC3, CV_16UC1,
CV_16UC3) with 'BGR' channel order, can be saved. If the depth or
channel order of the image is different,
use 'Mat::convertTo()' or 'cvtColor' functions to convert the image
to supporting format before using imwrite function.
The above program is very much similar to the program under 'Create
a Blank Image & Display' section in the lesson of Read & Display
Image. If you need further clarifications of any OpenCV functions
which are not explained here, please refer to Read & Display
Image lesson.
Summary
This program creates an yellowish image ( 3 channels, 16 bit image
depth, 650 high, 600 wide, (0, 50,000, 50,000) assigned for BGR
channels). Because the image has 16 bit depth, you can use values
between 0 and 65535 for each element in each channel. I have used
50,000 for each element in the green and red planes which gives the
yellowish color. You can try different values.
Then it specifies the compressing technique. I have used JPEG as the
compression technique in the above example. Then it saves the image
in the "D:/TestImage.jpg" location. Then it displays the newly
created image in a window and wait indefinitely until an user
presses a key.
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
if (!cap.isOpened())
// if not success, exit program
{
cout << "ERROR: Cannot open the video file" << endl;
return -1;
}
namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //crea
te a window called "MyVideo"
double dWidth =
cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of
frames of the video
double dHeight =
cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of
frames of the video
cout << "Frame Size = " << dWidth << "x" << dHeight << endl;
Size
frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));
while (1)
{
Mat frame;
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////
You can download this OpenCV visual c++ project from here. (The
downloaded file is a compressed .rar folder. So, you have to extract it
using Winrar or other suitable software)
VideoWriter::VideoWriter(const string&
filename, int fourcc, double fps, Size frameSize, bool isColor=true)
This is the constructor of the VideoWriter class. It initializes the object
with following parameters
o const string& filename - Specify the name and the location
of the output file. The video stream is written into this file
o int fourcc - specify the 4 character code for the codec which
is used to compress the video. Your computer may not be supported
some codecs. So, if you fail to save the video, please try other
codecs. Here are some popular codecs.
CV_FOURCC('D', 'I', 'V', '3') for DivX MPEG-4
codec
CV_FOURCC('M', 'P', '4', '2') for MPEG-4 codec
CV_FOURCC('D', 'I', 'V', 'X') for DivX codec
CV_FOURCC('P','I','M','1') for MPEG-1 codec
CV_FOURCC('I', '2', '6', '3') for ITU H.263 codec
CV_FOURCC('M', 'P', 'E', 'G') for MPEG-1 codec
Complete list of codec can be found here
Here I have used CV_FOURCC('P', 'I', 'M', '1') as the four character
code of codec to compress the video. If the output file cannot be
opened, you can try different four character code of codecs.
For Windows users, it is possible to use -1 instead of the above codecs
in order to choose compression method and additional compression
parameters from a dialog box. It is a best method for Microsoft
Windows users.
if ( !oVideoWriter.isOpened() )
Check whether the VideoWriter object initialize successfully. If not
exit the program immediately.
All other OpenCV functions have been discussed in earlier lessons. So,
if you are not familiar with those OpenCV functions yet, please go
through Capture Video from File or Camera
Filtering Images
Image filtering is an important part of computer vision. For most of
computer vision applications, filtering should be done before anything
else. OpenCV supports lots of in-build filtering methods for images.
Here is the list of filtering methods that I am going to discuss with
you in the following posts (with OpenCV 2.4.5 and C++ )
Here is the list of image filtering methods which are explained using
examples with OpenCV 2.1 in C style (not C++)
Eroding
Dilating
Inverting
Here is the original image which I am going to filter using above
methods.
Original Image
If you have not install and configure OpenCV yet, please refer
to Installing & Configuring with Visual Studio.
Eroding
Eroding is a simple way of filtering images. Here is how it can be
done with OpenCV.
///////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
int main()
{
//display the original image
IplImage* img = cvLoadImage("C:/MyPic.jpg");
cvNamedWindow("MyWindow");
cvShowImage("MyWindow", img);
cvWaitKey(0);
//cleaning up
cvDestroyWindow("MyWindow");
cvDestroyWindow("Eroded");
cvReleaseImage(&img);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////
You can download this OpenCV visual c++ project from here.
Eroded Image
New OpenCV functions which are not found earlier are explained
here
cvErode(img, img, 0, 2)
The 1st parameter is the source image.
The 2nd parameter is the destination image which is to be the eroded
image.
Here the 3rd parameter is the structuring element used for erosion. If
it is 0, a 3×3 rectangular structuring element is used.
The 4th parameter is the number of times, erosion is applied.
This function can process images in place. That means same variable
can be used for the 1st and 2nd parameters.
Dilating
Dilating is something like opposite of the eroding an image. Here is
the OpenCV code.
///////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
int main()
{
//display the original image
IplImage* img = cvLoadImage("C:/MyPic.jpg");
cvNamedWindow("MyWindow");
cvShowImage("MyWindow", img);
cvWaitKey(0);
//cleaning up
cvDestroyWindow("MyWindow");
cvDestroyWindow("Dilated");
cvReleaseImage(&img);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////
You can download this OpenCV visual c++ project from here.
Dilated Image
New OpenCV functions which are not found earlier are explained
here
cvDilate(img, img, 0, 2)
The 1st parameter is the source image.
The 2nd parameter is the destination image which is to be the dilated
image.
Here the 3rd parameter is the structuring element used for dilation. If
it is 0, a 3×3 rectangular structuring element is used.
The 4th parameter is the number of times, dilation is applied.
This function can process images in place. That means same variable
can be used for the 1st and 2nd parameters.
Inverting
Inverting an image is like taking the negative of an image.
///////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
int main()
{
//display the original image
IplImage* img = cvLoadImage("C:/MyPic.jpg");
cvNamedWindow("MyWindow");
cvShowImage("MyWindow", img);
cvWaitKey(0);
//cleaning up
cvDestroyWindow("MyWindow");
cvDestroyWindow("Inverted");
cvReleaseImage(&img);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////
You can download this OpenCV visual c++ project from here.
Inverted Image
Original Image
Note :
You may already notice that although the 1st pixel of the above
image should have (12 - 20) = -8, I have put 0. It is because
pixels never have negative values. Any pixel value is bounded
below by 0 and bounded above by 2^(bit depth).
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
if (img.empty())
{
cout << "Image cannot be loaded..!!" << endl;
return -1;
}
namedWindow("Original Image",
CV_WINDOW_AUTOSIZE);
namedWindow("High Brightness",
CV_WINDOW_AUTOSIZE);
namedWindow("Low Brightness",
CV_WINDOW_AUTOSIZE);
waitKey(0);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////
You can download this OpenCV visual c++ project from here. (The
downloaded file is a compressed .rar folder. So, you have to extract it
using Winrar or other suitable software)
Here is the original image.
original image
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
while(1)
{
Mat frame;
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////
Change Contrast of Image or Video
The easiest way to decrease the contrast is, multiplying each pixel value
by a number smaller than 1.
Contrast Increased
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
if (img.empty())
{
cout << "Image cannot be loaded..!!" << endl;
return -1;
}
Mat imgH;
img.convertTo(imgH, -1, 2, 0); //increase the contrast (double)
Mat imgL;
img.convertTo(imgL, -1, 0.5, 0); //decrease the contrast (halve)
//create windows
namedWindow("Original Image",
CV_WINDOW_AUTOSIZE);
namedWindow("High Contrast",
CV_WINDOW_AUTOSIZE);
namedWindow("Low Contrast",
CV_WINDOW_AUTOSIZE);
Original Image
//create windows
namedWindow("Original
Video",CV_WINDOW_AUTOSIZE);
namedWindow("Contrast
Increased",CV_WINDOW_AUTOSIZE);
namedWindow("Contrast
Decreased",CV_WINDOW_AUTOSIZE);
while (1)
{
Mat frame;
Mat imgH;
frame.convertTo(imgH, -1, 2, 0); //increase the contrast
(double)
Mat imgL;
frame.convertTo(imgL, -1, 0.5, 0); //decrease the contrast
(halve)
All the OpenCV methods in the above example program have been
discussed in previous lessons. So, I am not going to repeat them again.
Histogram Equalization of Grayscale or Color Image
Histogram
Histogram is the intensity distribution of an image.
E.G -
Consider the following image. Say, depth of the image is 2 bits.
Therefore the value range for each and every pixel is from 0 to 3.
Histogram of the a image shows how the pixel values are distributed.
As you can see in the above image there are 5 pixels with value 0, 7
pixels with value 1, 9 pixels with value 2 and 4 pixels with value 3.
These information is tabulated as follows.
Histogram Equalization
Histogram Equalization is defined as equalizing the intensity
distribution of an image or flattening the intensity distribution curve.
Histogram equalization is used to improve the contrast of an image.
The equalized histogram of the above image should be ideally like the
following graph.
Equalized Histogram
But practically, you cannot achieve this kind of perfect histogram
equalization. But there are various techniques to achieve histogram
equalization close to the perfect one. In OpenCV, there is an in-built
OpenCV function to equalize histogram.
/////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
if (img.empty())
{
cout << "Image cannot be loaded..!!" << endl;
return -1;
}
//create windows
namedWindow("Original Image",
CV_WINDOW_AUTOSIZE);
namedWindow("Histogram Equalized",
CV_WINDOW_AUTOSIZE);
return 0;
}
/////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
You can download this OpenCV visual c++ project from here. (The
downloaded file is a compressed .rar folder. So, you have to extract it
using Winrar or other suitable software)
Original Image
/////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
vector<Mat> channels;
Mat img_hist_equalized;
//create windows
namedWindow("Original Image", CV_WINDOW_AUTOSIZE);
namedWindow("Histogram Equalized",
CV_WINDOW_AUTOSIZE);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////
You can download this OpenCV visual c++ project
from here. (The downloaded file is a compressed .rar folder. So,
you have to extract it using Winrar or other suitable software)
Original Color Image
Argument list
o const Mat& m - Input multi-channel array
o vector<Mat>& mv - vector that stores the each
channel of the input array
equalizeHist(channels[0], channels[0]);
Here we are only interested in the 1st channel (Y) because
it represents the intensity information whereas other two
channels (Cr and Cb) represent color components. So, we
equalize the histogram of the 1st channel using OpenCV in-built
function, 'equalizeHist(..)' and other two channels remain
unchanged.
cvtColor(img_hist_equalized, img_hist_equalized,
CV_YCrCb2BGR)
This line converts the image from YCrCb color space to BGR
color space. It is essential to convert to BGR color space
because 'imshow(..)' OpenCV function can only show images
with that color space.
Homogeneous Smoothing
"Homogeneous Smoothing" is also called as "Homogeneous
Blurring", "Homogeneous Filtering" or "Box Blurring". This is the
most simplest method of smoothing an image. It takes simply
the average of the neighbourhood of a pixel and assign that
value to itself.
You have to choose right size of the kernel. If it is too large,
small features of the image may be disappeared and image will
look blurred. If it is too small, you cannot eliminate noises of the
image.
OpenCV code
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
Mat dst;
char zBuffer[35];
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////
You can download this OpenCV visual C++ project from here.
Original Image
Smoothed Image - Because of the kernel size is too large, the image
looks blurry
Explanation of New OpenCV Functions
Gaussian Smoothing
OpenCV Code
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
Mat dst;
char zBuffer[35];
for ( int i = 1; i < 31; i = i + 2 )
{
//copy the text to the "zBuffer"
_snprintf_s(zBuffer, 35,"Kernel Size : %d x %d", i, i);
//smooth the image using Gaussian kernel in the "src" and save
it to "dst"
GaussianBlur( src, dst, Size( i, i ), 0, 0 );
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////
You can download this OpenCV visual C++ project from here.
Median Smoothing
OpenCV Code
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
Mat dst;
char zBuffer[35];
return 0;
}
/////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
You can download this OpenCV visual C++ project from here.
Bilateral Smoothing
OpenCV Code
Mat dst;
char zBuffer[35];
( If you have not install and configure OpenCV yet, please refer
to Installing & Configuring with Visual Studio. )
// Create a window
namedWindow("My Window", 1);
while (true)
{
//Change the brightness and contrast of the image (For
more infomation http://opencv-srf.blogspot.com/2013/07/change-
contrast-of-image-or-video.html)
Mat dst;
int iBrightness = iSliderValue1 - 50;
double dContrast = iSliderValue2 / 50.0;
src.convertTo(dst, -1, dContrast, iBrightness);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////
You can download this OpenCV visual c++ example from here.
All other functions have been discussed in the previous lessons. If you
have not followed them yet, please visit
Read & Display Image
Change Contrast of Image or Video
which have the all the other OpenCV functions in the above example
code.
///////////////////////////////////////////////////////////////////////////////////////
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
Mat src;
// Create a window
namedWindow("My Window", 1);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////
You can download this OpenCV visual c++ project from here.
Trackbar with Callback Function
Explanation
Here is the simple OpenCV code to detect left, right and middle mouse
clicks and mouse movements with its coordinates
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
}
}
//Create a window
namedWindow("My Window", 1);
return 0;
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////
You can download this OpenCV visual C++ project from here
Detect Mouse Clicks and Moves Over the OpenCV Window
Summary
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
//Create a window
namedWindow("My Window", 1);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////
You can download this visual C++ OpenCV project from here.
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
while (true)
{
Mat matRotation = getRotationMatrix2D(
Point(iImageWidth, iImageHieght), (iAngle - 180), 1 );
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////
You can download this visual C++ project from here.
Original Image
Rotated Image
Explanation
Here is the explanation for new OpenCV functions which are not
found in previous lessons.
Mat getRotationMatrix2D( Point2f center, double angle,
double scale )
Arguments -
Arguments -
o src - Source Image
o dst - Destination image which should have the same
type as the source image(The transformed image is stored in
this location)
o M - 2x3 affine transformation matrix
o dsize - Size of the destination image
o flags - Interpolation methods
o borderMode - pixel extrapolation method. (Try these
values; BORDER_REPLICATE, BORDER_CONSTANT, BORD
ER_REFLECT, BORDER_WRAP, BORDER_REFLECT_101,
BORDER_TRANSPARENT and BORDER_ISOLATED)
o borderValue - If you use BORDER_CONSTANT
for borderMode, this argument define the value used for the
border
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
iImageCenterY = imgOriginal.rows / 2;
iImageCenterX = imgOriginal.cols / 2;
int iDummy = 0;
CallbackForTrackBar(iDummy, &iDummy);
waitKey(0);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////
You can download this visual C++ project from here.
Rotate a Video
Rotating a video is also simple. The code is just like the 1st
example in this lesson. Here is the OpenCV C++ code.
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
while (true)
{
Mat matOriginalFrame;
// read a new frame from video
bool bSuccess = cap.read(matOriginalFrame);
imshow(pzOriginalWindowName, matOriginalFrame);
//wait for 'esc' key press for 30 ms. If 'esc' key is pressed,
break loop
if (waitKey(30) == 27)
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////
You can download this visual C++ project from here.
The easiest way to detect and segment an object from an image is the
color based methods . The object and the background should have a
significant color difference in order to successfully segment
objects using color based methods.
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
namedWindow("Control",
CV_WINDOW_AUTOSIZE); //create a window called
"Control"
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
while (true)
{
Mat imgOriginal;
Mat imgHSV;
cvtColor(imgOriginal, imgHSV,
COLOR_BGR2HSV); //Convert the captured frame from
BGR to HSV
Mat imgThresholded;
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////
You can download this OpenCV visual c++ project from here.
Explanation
In the above image, each small box represents a pixel of the image. In
real images, these pixels are so small that human eye cannot
differentiate.
Usually, one can think that BGR color space is more suitable for color
based segmentation. But HSV color space is the most suitable color
space for color based image segmentation. So, in the above
application, I have converted the color space of original image of the
video from BGR to HSV image.
How to find the exact range of HUE, SATURATION and VALUE for
a object is discussed later in this post.
After thresholding the image, you'll see small white isolated objects
here and there. It may be because of noises in the image or the actual
small objects which have the same color as our main object.
These unnecessary small white patches can be eliminated by
applying morphological opening. Morphological opening can be
achieved by a erosion, followed by the dilation with the same
structuring element.
Arguments -
o InputArray src - Source image
o InputArray lowerb - Inclusive lower boundary
(If lowerb=Scalar(x, y, z), pixels which have values lower than x, y
and z for HUE, SATURATION and VALUE respectively is
considered as black pixels in dst image)
o InputArray upperb - Exclusive upper boundary (If it
is upperb=Scalar(x, y, z), pixels which have values greater or
equal than x, y and z for HUE, SATURATION and VALUE
respectively is considered as black pixels in dst image)
o OutputArray dst - Destination image (should have the
same size as the src image and should be 8-bit unsigned integer,
CV_8U)
void erode( InputArray src, OutputArray dst,
InputArray kernel, Point anchor=Point(-1,-1), int
iterations=1, int borderType=BORDER_CONSTANT, const
Scalar& borderValue=morphologyDefaultBorderValue() )
This function erode the source image and stores the result in
the destination image. In-place processing is supported. (which
means you can use the same variable for the source and
destination image). If the source image is multi-channel, all
channels are processed independently and the result is stored
in the destination image as separate channels.
Arguments -
o InputArray src - Source image
o OutputArray dst - Destination image (should have
the same size and type as the source image)
o InputArray kernel - Structuring element which is
used to erode the source image
o Point anchor - Position of the anchor within the
kernel. If it is Point(-1, -1), the center of the kernel is taken as
the position of anchor
o int iterations - Number of times erosion is applied
o int borderType - Pixel extrapolation method in a
boundary condition
o const Scalar& borderValue - Value of the pixels in
a boundary condition if borderType = BORDER_CONSTANT
int borderType=BORDER_CONSTANT,
const Scalar&
borderValue=morphologyDefaultBorderValue() );
This function dilate the source image and stores the result in
the destination image. In-place processing is supported. (which
means you can use the same variable for the source and
destination image). If the source image is multi-channel, all
channels are processed independently and the result is stored
in the destination image as separate channels.
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
namedWindow("Control",
CV_WINDOW_AUTOSIZE); //create a window called "Control"
while (true)
{
Mat imgOriginal;
Mat imgHSV;
cvtColor(imgOriginal, imgHSV,
COLOR_BGR2HSV); //Convert the captured frame from BGR to
HSV
Mat imgThresholded;
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV),
Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold
the image
// if the area <= 10000, I consider that the there are no object in
the image and it's because of the noise, the area is not zero
if (dArea > 10000)
{
//calculate the position of the ball
int posX = dM10 / dArea;
int posY = dM01 / dArea;
if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0)
{
//Draw a red line from the previous point to the current point
line(imgLines, Point(posX, posY), Point(iLastX, iLastY),
Scalar(0,0,255), 2);
}
iLastX = posX;
iLastY = posY;
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////
You can download this OpenCV visual c++ project from here.
Object Tracking
Explanation
0th order central moments of the binary image is equal to the white
area of the image in pixels.
Now, let's discuss new OpenCV methods that can be found in the
above application.
How to Find Exact Range for 'Hue', 'Saturation' and 'Value' for a
Given Object
Now you can find the optimum HUE, SATURATION and VALUE
ranges for the object. It is 163-179, 126-217 and 68-127 in my case as
you can see in the below picture.
Shape Detection & Tracking using Contours
In the previous tutorial, we could detect and track an
object using color separation. But we could not identify
the shape of the object there. In this tutorial, let's see
how to identify a shape and position of an object using
contours with OpenCV.
Let's see how this can be done with OpenCV. All you
need, is a binary image in which your objects should be
white and the background should be black.
Now I am going to identify triangles and quadrilaterals
and heptagon in the above image using a
C++ application with OpenCV. I'll draw a line along
the perimeter of every identified polygon with colors
blue for triangle, green for quadrilaterals and red for
heptagons. Here is the code.
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
using namespace std;
int main()
{
IplImage* img
= cvLoadImage("C:/Users/SHERMAL/Desktop/FindingCont
ours.png");
cvThreshold(imgGrayScale,imgGrayScale,128,255,CV_THR
ESH_BINARY);
//cleaning up
cvDestroyAllWindows();
cvReleaseMemStorage(&storage);
cvReleaseImage(&img);
cvReleaseImage(&imgGrayScale);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
You can download this OpenCV visual c++ project from here. (The
downloaded file is a compressed .rar folder. So, you have to extract it
using Winrar or other suitable software)
Explanation
Here I have converted the original image in to gray
scale. It is because this method works only with gray
scale image with single channel. To get better results, I
threshold the gray-scale image using 'cvThreshold'
function. You can use your own way to threshold the
image. Then I find all contours in the thresholded
image and identify and track all triangles,
quadrilaterals and heptagons.
Arguements -
o const Mat& src - Source array (This should be
single channel)
o Mat& dst - Destination array which has the
same size and same type as the 'src'
o double threshVal - Threshold value
o double max - Maximum value to use
with 'THRESH_BINARY' and 'THRESH_BINARY_INV'
which are thresholding types
o int thresholdType - You can use one of the
following for this arguement
THRESH_BINARY
dst(x,y)=max, if src(x,y) >
ThreshVal
dst(x,y)=0, if src(x,y) <
ThreshVal
THRESH_BINARY_INV
dst(x,y)=0, if src(x,y) >
ThreshVal
dst(x,y)=max, if src(x,y) <
ThreshVal
THRESH_TOZERO
dst(x,y)=src(x,y), if src(x,y) > ThreshVal
dst(x,y)=0, if src(x,y) < ThreshVal
THRESH_TOZERO_INV
dst(x,y)=0, if src(x,y) >
ThreshVal
dst(x,y)=src(x,y), if src(x,y) <
ThreshVal
THRESH_TRUNC
dst(x,y)=threshVal, if src(x,y) >
ThreshVal
dst(x,y)=src(x,y), if src(x,y) <
ThreshVal
cvReleaseMemStorage( CvMemStorage** storage
)
Deallocate memory blocks which have been allocated
by 'cvCreateMemStorage()' function
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
using namespace std;
int main()
{
IplImage* img
= cvLoadImage("C:/Users/SHERMAL/Desktop/DetectingCo
ntours.jpg");
cvNamedWindow("GrayScale Image");
cvShowImage("GrayScale Image",imgGrayScale);
//thresholding the grayscale image to get better results
cvThreshold(imgGrayScale,imgGrayScale,100,255,CV_THR
ESH_BINARY_INV);
cvNamedWindow("Thresholded Image");
cvShowImage("Thresholded Image",imgGrayScale);
//if there are 3 vertices in the contour and the area of the
triangle is more than 100 pixels
if(result->total==3 && fabs(cvContourArea(result,
CV_WHOLE_SEQ))>100 )
{
//iterating through each point
CvPoint *pt[3];
for(int i=0;i<3;i++){
pt[i] = (CvPoint*)cvGetSeqElem(result, i);
}
//cleaning up
cvDestroyAllWindows();
cvReleaseMemStorage(&storage);
cvReleaseImage(&img);
cvReleaseImage(&imgGrayScale);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
You can download this OpenCV visual c++ project
from here. (The downloaded file is a compressed .rar folder.
So, you have to extract it using Winrar or other suitable
software)
Triangles Detected
Explanation
fabs(double x)
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
using namespace std;
IplImage* imgTracking=0;
lastX1 = posX;
lastY1 = posY;
}
else{
if(lastX2>=0 && lastY2>=0 &&
posX>=0 && posY>=0){
// Draw a blue line from the
previous point to the current point
cvLine(imgTracking, cvPoint(posX,
posY), cvPoint(lastX2, lastY2), cvScalar(255,0,0),
4);
}
lastX2 = posX;
lastY2 = posY;
}
}
cvReleaseMemStorage(&storage);
}
int main(){
//load the video file to the memory
CvCapture *capture
= cvCaptureFromAVI("E:/Projects/Robot/IESL
Robot/robot/a.avi");
if(!capture){
printf("Capture failure\n");
return -1;
}
IplImage* frame=0;
frame = cvQueryFrame(capture);
if(!frame) return -1;
cvNamedWindow("Video");
frame = cvQueryFrame(capture);
if(!frame) break;
frame=cvCloneImage(frame);
cvCvtColor(frame,imgGrayScale,CV_BGR2GRAY);
cvThreshold(imgGrayScale,imgGrayScale,100,255
,CV_THRESH_BINARY_INV);
cvShowImage("Video", frame);
//Wait 10mS
int c = cvWaitKey(10);
//If 'ESC' is pressed, break the loop
if((char)c==27 ) break;
}
cvDestroyAllWindows();
cvReleaseImage(&imgTracking);
cvReleaseCapture(&capture);
return 0;
}
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////
You can download this OpenCV visual c++ project
from here. (The downloaded file is a compressed .rar folder.
So, you have to extract it using Winrar or other suitable
software)
Explanation