Monday, August 22, 2011

Episode_15_Smart_Camera (haarcascades)



In general, we only know that function of digital camera as take a picture or record the image and save the photographs on the digital memory cards, but keeping up with technology, camera can be smarter that can detect our face, eyes, mouth, and fullbody. Of course, it's very useful to help people identification quickly and accuratel for Home security or other.
In electrical engeenerng, we already know some kinds of sensor such as ultrasonic, LM35, photodioda, etc. How about using camera as a sensor !! Well, in this episode, I will share my experiment when I was learning to detect faces with haarcascades. This method just for beginer who want detect faces easily without using hard artificial intelligence systems such as eigenfaces and neural network. So what are you waiting for, Let's try. (Talk Less Do More)

Ok, First you need to copy haarcascades data into your project before you run your program.


picture 0_haarcascades_data


This source code :

/**
* Display video from webcam and detect faces
*/
#include "stdio.h"
#include "cv.h"
#include "highgui.h"

CvHaarClassifierCascade *cascade;
CvMemStorage            *storage;
int key;

void detectFaces( IplImage *img );

int main( int argc, char** argv )
{
CvCapture *capture;
IplImage  *frame;
char      *filename = "haarcascade_frontalface_alt2.xml";

/* load the classifier
note that I put the file in the same directory with
this code */
cascade = ( CvHaarClassifierCascade* )cvLoad( filename, 0, 0, 0 );

/* setup memory buffer; needed by the face detector */
storage = cvCreateMemStorage( 0 );

/* initialize camera */
capture = cvCaptureFromCAM( 0 );
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 320 );
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 240 );

/* always check */
assert( cascade && storage && capture );

/* create a window */
cvNamedWindow( "video", 1 );

while( key != 'q' ) {

/* get a frame */
frame = cvQueryFrame( capture );
/* always check */
if( !frame ) break;

/* detect faces and display video */
detectFaces( frame );

/* quit if user press 'q' */
key = cvWaitKey( 10 );
}

/* free memory */
cvReleaseCapture( &capture );
cvDestroyWindow( "video" );
cvReleaseHaarClassifierCascade( &cascade );
cvReleaseMemStorage( &storage );

return 0;
}

void detectFaces( IplImage *img )
{
int i;

/* detect faces */
CvSeq *faces = cvHaarDetectObjects(
  img,
  cascade,
  storage,
  1.1,
  3,
  0 /*CV_HAAR_DO_CANNY_PRUNNING*/,
  cvSize( 40, 40 ) );

/* for each face found, draw a red box */
for( i = 0 ; i < ( faces ? faces->total : 0 ) ; i++ ) {
CvRect *r = ( CvRect* )cvGetSeqElem( faces, i );
cvRectangle( img,
           cvPoint( r->x, r->y ),
           cvPoint( r->x + r->width, r->y + r->height ),
           CV_RGB( 255, 0, 0 ), 1, 8, 0 );
}

/* display video */
cvShowImage( "video", img );
}

0 comments:

Post a Comment