samedi 14 septembre 2013

How to read / list directory and its subdirectories with C++ ?

A simple way to read or list files or directories is to use Dirent Lib which can be downloaded from here and installed in the same way as it was shown for OpenCV Lib here (if you are using Microsoft Visual C++ Express) or here (if you are using Visual Studia 2010)
Actually I need this Lib to read an image database where I have many directories and each one have a different number of images. So I can't use a constant number to read every directory, that's why I have turned to use Dirent Lib.
Here I give an example to show how to use  it:

# include <dirent.h> 
#include "stdafx.h" 
#include <highgui.h>

void main()
  DIR *pDIR;
  struct dirent *entry;
  if( pDIR = opendir(ClassPath.c_str()) )
         while(entry = readdir(pDIR))
                 if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 )

                          // Specify image path
                           string ImgPath = stra  + "/" + entry->d_name ;
                          //Load the image
                           IplImage* Src = cvLoadImage(ImgPath.c_str());

                          // Then here ...You can add any processing you want for that image/file !
                           Blablabliblou ......
                        //Free Memory


mercredi 17 juillet 2013

Extract Circular/Elliptical ROI using OpenCV

It is well known that OpenCV manage rectangular region of interest (ROI) and not Circular or elliptical regions. So as to crop a circular or elliptical region of interest, there is a simple trick by applying a (circular/elliptical) binary mask on the image.
Here i'm going to show an example of using mask to extract elliptical/circular region for face detection task.
Actually this help to get rid of hair, background, neck, and all the noisy things which can appear jointly with the face.

void main()
   //----->Load image
     IplImage* Src = cvLoadImage("C:/ Test.jpg");

  //----->Face detection function
   CvRect* FaceD;
   FaceDetection(Src, FaceD); //This function is already defined, it returns the position of the face 

  //----->Extract the elliptical region of the face
        //Crop the rectangular region of the face   + convert it to grayscale image   
        CvRect ROIRect = cvRect(FaceD->x, FaceD->y, FaceD->width, FaceD->height );               
        CvSize ROISize= cvSize(FaceD->width, FaceD->height );               
        IplImage* ImgROI =  cvCreateImage( ROISize, Src->depth, Src->nChannels);   
        cvSetImageROI(Src, ROIRect);               
        cvCopy(Src, ImgROI, NULL);               
        IplImage* ImgROIGray = cvCreateImage( ROISize, IPL_DEPTH_8U, 1);
        cvCvtColor(ImgROI, ImgROIGray, CV_RGB2GRAY );                 
        //Encircle the face

        CvPoint FaceCenter = cvPoint(FaceD->width/2,FaceD->height/2);
        IplImage *res = cvCreateImage(Size(ImgROI->width,ImgROI->height), IPL_DEPTH_8U, 1);
        IplImage *roi = cvCreateImage(Size(ImgROI->width,ImgROI->height), IPL_DEPTH_8U, 1);
        cvEllipse(roi, FaceCenter, cvSize(FaceD->width/2*0.85, FaceD->height/2*1.05), 0.0, 0.0, 360.0,    CV_RGB(255,255,255), -1, 8, 0);
        cvAnd(ImgROIGrayEq, ImgROIGrayEq, res, roi); 

        cvNamedWindow("win");cvShowImage("win", res);cvWaitKey(10);            


mercredi 22 mai 2013

Continuous and Discrete Data

What's a data?
  • Data is a collection of facts, such as values or measurements. 
  • It can be numbers, words, measurements, observations or even just descriptions of things. 
  • It can be qualitative or quantitative: the qualitative data describe information (it describes something)  and the quantitative data give numerical information (numbers).
Discrete Data 
  • Discrete data can only take particular values. Discrete data can be numeric,  like numbers of apples, but it can also be categorical like red or blue, or male or female, or good or bad.
  • Discrete data usually occurs in a case where there are only a certain number of values, or when we are counting something (using whole numbers).
  • For example: number of pages in book, shoes size, Number of people in race, they are all a discrete since they can only take an individual values.
Continuous Data 
  • Continuous data are not restricted to defined separate values, but can occupy any value over a continuous range. Between any two continuous data values there may be an infinite number of others. Continuous data are always essentially numeric.
  • For example: the height of trees at a nursery is an example of continuous data. Is it possible for a tree to be 76.2" tall? Sure. How about 76.29"? Yes. How about 76.2914563782"?  The possibilities depends upon the accuracy of our measuring device. 
To conclude...
One general way to tell if data is continuous is to ask yourself if it is possible for the data to take on values that are fractions or decimals. If your answer is yes, this is usually continuous data. 
What do we know about the Cat arrow ?
Qualitative Data:
-He is brown and black
-He has long hair
-He has lots of energy 

Quantitative Data:
-Discrete Data: He has 4 legs. He has 6 brothers. ect
-Continuous Data: He weighs 5.5 kg. He is 57 mm tall. ect

samedi 27 avril 2013

Memory Managment in OpenCV_C++

Unlike Java language, C++ isn't a garbage collector, therefore you need to manually deallocates memory every time its use is over. If you ignore this detail, you will have out-of-memory problem since your RAM couldn't supply all the space you are asking for. So you need to know perfectly handling the memory space you are using.
In the following sections I will show briefly how to get rid of allocated memory.

new and delete
if you allocate memory using new, you compulsorily deallocate memory using delete operator:
- Memory allocation/deallocation for an integer
// allocate memory using new operator 
int *var = new int
//deallocates memory using delete operator 
delete var;
- Memory allocation/deallocation for a table
//Allocate table of 100 elements
int *a = new int[100];
//Delete the array element
delete [] a; a = NULL;

create and release
To fix the memory leak problems with OpenCV, you should check if you have release the object you have already created. In OpenCV there are many create function and their corresponding release function. If you are creating something and want later to return it, make sure that you didn't release it. 
Here some list of the most used functions:
CvSeq -- > cvClearSeq
CvMemStorage --> cvReleaseMemStorage
CvHaarClassifierCascade --> cvReleaseHaarClassifierCascade
cvCreateImageHeader –-> cvReleaseImageHeader
cvCreateImage –-> cvReleaseImage
cvCreateMat –-> cvReleaseMat
cvCreateMatND –-> cvReleaseMatND
cvCreateData –-> cvReleaseData
cvCreateSparseMat –-> cvReleaseSparseMat
cvCreateGraphScanner –-> cvReleaseGraphScanner
- cvOpenFileStorage –-> cvReleaseFileStorage
cvAlloc –-> cvFree
- ... etc.

If you have create a table of image, before releasing the table (with delete) you need to go over each table case and release the allocated image (of course after its use is over). Here is an example:
// Allocation of table of images
IplImage** TabImg = new IplImage* [NbImage];
for(int i=0; i<NbImage; i++)
{TabImg[i]=cvCreateImage(cvSize(100, 100), IPL_DEPTH_8U, 1); }
// Use the Table of image 
//Free the Table of images
for(int i=0; i<NbImage; i++)
 {cvReleaseImage(&TabImg[i]);} //Free each table case
 delete[] TabImg; TabImg = NULL; //Free the tale itself

Then your memory is pretty free ...

Freedom is good not only for human but also for memory ;-)

mercredi 27 mars 2013

How to install OpenCV 3.2.1 on Visual Studio 2010 ( Windows XP)

This tutorial assumes that you have already installed Microsoft Visual Studio 2010 and downloaded the library OpenCV 3.2.1( here...)
These step are supposed to be done for every new project in Visual Studio 2010 (Not like Microsoft Visual Express, it is supposed to be configurated just one time)
  1. Create your new project.
  2. Go to Project>Properties>Configuration Properties>VC++ Directories>Include Directories (<Edit...>) then add the path of include files: D:\opencv2.3.1\build\include
  3. Go to Project>Properties>Configuration Properties>Linker> General > Additional Library Directories (<Edit...>) and add Library path: D:\opencv2.3.1\build\x86\vc10\lib
  4. Go to Project>Properties>Configuration Properties>Linker > Input > Additional Dependencies and add all library you are going to use in your project (Here I will mention the main used Lib)

  5. Don't forget to add the path of the bin file (D:\opencv2.3.1\build\x86\vc10\bin) in the Environment Variables dialogue (the System Variables box select Path and then Edit).

dimanche 24 février 2013

What is biometric?

A biometric is a measurement of a biological characteristic such as fingerprint, iris pattern, retina image, face  or a behavioural characteristic such as voice, gait or signature. Using biometrics for identifying human beings offers some unique advantages. Biometrics can be used to identify you as you using some biometric  characteristics to identify individuals automatically. Biometric characteristic are very interesting since they are universally present, unique to the individual, stable over time and easily measurable.
Actually biometrics can be used to answer two principal questions:
• Are you who you claim to be?
• Who are you?
  • Are you who you request to be?

Confirming that someone is who they request to be usually relies on something that they possess, such as a security pass, or something that they know, such as a password. Nontheles nothing can provide absolute confidence as security passes can be stolen and passwords are often written down. 
Biometric technology offers an additional level of confidence, but with the disadvantage that, unlike a password, a person’s characteristics are not secret and can therefore be copied. To confirm an individual’s identity, their biometric is scanned, converted into electronic form and stored either on a card that remains in their possession or in a database.
  • Who are you?

It is possible to answer the question ‘who are you?’ if you are saved in the system database .The biometric of the unknown person is compared against the database in a ‘one-to-many’ search. Their identity can be determined if their biometric has been entered onto the database on a previous occasion.

jeudi 21 février 2013

OpenCV supports Java on desktop

As of OpenCV 2.4.4, OpenCV supports desktop Java development using nearly the same interface as for Android development. This guide will help you to create your first Java (or Scala) application using OpenCV. Here... 

mercredi 13 février 2013

Draw an Arrow with OpenCV (and python version too)

OpenCV does not provide functions to draw an arrow. We will introduce a simple way to do it!
First, we draw a simple line (easy). Then, we plot the two segments that represent the arrow. These segments present an angle of 45 degrees (pi / 4) with the main line.
Here is the code for that:
#include <stdio.h>
#include <cv.h>
#include <highgui.h>

void drawArrow(IplImage *image, CvPoint p, CvPoint q, CvScalar color, int arrowMagnitude = 9, int thickness=1, int line_type=8, int shift=0) 

    //Draw the principle line
    cvLine(image, p, q, color, thickness, line_type, shift);
    const double PI = 3.141592653;
    //compute the angle alpha
    double angle = atan2((double)p.y-q.y, (double)p.x-q.x);
    //compute the coordinates of the first segment
    p.x = (int) ( q.x +  arrowMagnitude * cos(angle + PI/4));
    p.y = (int) ( q.y +  arrowMagnitude * sin(angle + PI/4));
    //Draw the first segment
    cvLine(image, p, q, color, thickness, line_type, shift);
compute the coordinates of the second segment
    p.x = (int) ( q.x +  arrowMagnitude * cos(angle – PI/4));
    p.y = (int) ( q.y +  arrowMagnitude * sin(angle – PI/4));
Draw the second segment
    cvLine(image, p, q, color, thickness, line_type, shift);

//How to call this function
int main()


   IplImage *canvas = cvCreateImage(cvSize(320, 240), IPL_DEPTH_8U, 3);
    drawArrow(canvas, cvPoint(10, 20), cvPoint(100, 150), CV_RGB(100, 0, 255), 20);
    cvShowImage(“win”, canvas);
    return 1;


vendredi 8 février 2013

How to install OpenCV 2.3 on Microsoft Visual C++ Express 2008 (Windows XP)

OpenCV is an open source computer vision library available from here .... The library is written in C and C++ and runs under Linux, Windows and Mac OS X. There is active development on interfaces for Python, Ruby, Matlab, and other languages.  

OpenCV was conceived as a way to make computer vision infrastructure universally available. With the aid of Intel’s Performance Library Team,* OpenCV started with a core of implemented code and algorithmic specifications being sent to members of Intel’s Russian library team. This is the “where” of OpenCV: it started in Intel’s research lab with collaboration from the Soft ware Performance Libraries group together with implementation and optimization expertise in Russia.

For more details of OpenCV, I recommend this book :"Learning OpenCV Computer Vision With The OpenCV Library" which could be found on this link.

This tutorial assumes that you have already installed Microsoft Visual C++ Express 2008 and includes the following steps:
  1. Step1: Downloading and Installing OpenCV OpenCV 
  2. Step2: Include the Bin File and Lib File 
  3. Step3: Configure Visual Studio to use OpenCV 
  4. Setp4:Create a sample project which makes use of OpenCV 2.3

Step1: Downloading and Installing OpenCV 2.3
Go to the folder where you downloaded the executable file and select “Run as Administrator”.
The executable file is essentially an archive of files with an extractor built in. It will ask you to select the location where you would like it to extract all its contents. Select for exemple C:\ as the path and click Extract. It will create a folder called opencv2.3 with the path: C:\opencv2.3

Step2: Include the Bin File and Lib File 
Add the path of the bin and lib file in the ( C:\opencv2.3\build\x86\vc9\lib and C:\opencv2.3\build\x86\vc9\bin ) Environment Variables dialogue (the System Variables box select Path and then Edit).

Step3: Configure Visual Studio to use OpenCV :

* Add Executable, Include and Lib File
This step is done only one time while installing OpenCV Bib:
1- Open Visual C++ Express 2008
2- Go to Tools →  Options → Project and Solution → VC++ Directories
3- Select in the right combox Binary file and add the binary file located in C:\opencv2.3\build\x86\vc9\bin
4-  Select in the right combox Include file and add the three path of Include file located respectively in
5-  Select in the right combox Bib file and add the bib file located in 

* Add Lib File
This step is done for every new Visual C++ Project:
 1- Go to Project → Properties  → Configuration properties  →  Liker  → Input  → Additional Dependencies  and add the bib that you are ging to use, for exemple:
  opencv_core231d.lib  opencv_imgproc231d.lib  opencv_highgui231d.lib  opencv_ml231d.lib  opencv_video231d.lib  opencv_features2d231d.lib  opencv_calib3d231d.lib  opencv_objdetect231d.lib  opencv_contrib231d.lib  opencv_legacy231d.lib  opencv_flann231d.lib

2- Click Apply then OK

Setp4:Create a sample project which makes use of OpenCV 2.3
1- Click File → New →Project
2- In the “Installed Templates” box choose Visual C++ → Win32 and select Win32 Console Application
3- Enter a name for the project and specify  the location where you would like to save your project and then click OK
4- Select the Application setting and shoot the Precompiled header and then clich on Finish. 
5- Click on the right of your mouse on the source file  → Add new element →  specify the name of our file, for example "Test.cpp" then click on Add
6- Type the following code on your Test.cpp File:

 #include "stdafx.h"
 #include <highgui.h>
int _tmain(int argc, _TCHAR* argv[])

     int c;

     // allocate memory for an image

     IplImage *img;

     // capture from video device #1

     CvCapture* capture = cvCaptureFromCAM(1);

     // create a window to display the images

     cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);

     // position the window

     cvMoveWindow("mainWin", 5, 5);



         // retrieve the captured frame


         // show the image in the window

         cvShowImage("mainWin", img );

         // wait 10 ms for a key to be pressed


         // escape key terminates program

         if(c == 27)



  return 0;


vendredi 3 février 2012

Traffic Sign Recognition System

The traffic sign recognition system, an intelligent vision system for recognizing the traffic signs, becomes important in an autonomous vehicle. It will provide information of the road signs on the way and guide the vehicle when running in the street. In driver assistance systems, it helps the driver to recognize the road signs early and accurately. A false recognition of the traffic signs caused by the human factors could be avoided. Thus, the traffic sign recognition system makes the driving safer and easier.

In the outdoor environment, due to the illumination changes, rotation, shadows, and partial occlusion of the images, the traffic sign recognition becomes a challenging task. Furthermore, a fast algorithm is needed to operate in the real time environment. Generally, the traffic sign recognition system is divided into two stages: the detection stage, which finds the region of interest containing the traffic signs from an image, and the classification stage where the detected signs are classified into one of the road signs.

Source : A. Soetedjo, K. Yamada"Fast and Robust Traffic Sign Detection",2005 IEEE International Conference on Systems, Man and Cybernetics, Hawaii, October 2005