Search code examples
copencvimage-processingcomputer-visionface-detection

Detecting a face and saving the detected face in OpenCV


I am trying to detect the face in the image and trying to save the detected face as an image in OpenCV.

Having some problems in the detectfaces function below.

#include "stdafx.h"

#include <stdio.h>
#include <cv.h>
#include <highgui.h>
#include <cxcore.h>

CvHaarClassifierCascade *cascade;
CvMemStorage            *storage;

void detectFaces( IplImage *img );

int _tmain(int argc, _TCHAR* argv[])
{
  //CvCapture *capture;
  IplImage  *img;//*out;
  int       key = 0;
  char      *filename = "C:/OpenCV2.1/data/haarcascades/haarcascade_frontalface_alt.xml";

  cascade = ( CvHaarClassifierCascade* )cvLoad( filename, 0, 0, 0 );
  storage = cvCreateMemStorage( 0 );
  img     = cvLoadImage("Yurico.png");

  assert( cascade && storage && img );

  cvNamedWindow( "video:", 1 );
  //cvNamedWindow( "video1:", 1 );
  //out = detectFaces( img );
  detectFaces( img );
  cvWaitKey( 0 );
  //cvShowImage( "video", out );
  cvDestroyWindow( "video:" );
  //cvDestroyWindow( "video1:" );
  cvReleaseImage( &img );
  cvReleaseHaarClassifierCascade( &cascade );
  cvReleaseMemStorage( &storage );

  return 0;
}

void detectFaces( IplImage *img )
{
    int i;
     CvRect *r;
    CvSeq *faces = cvHaarDetectObjects(
            img,
            cascade,
            storage,
            1.1,
            3,
            0 /*CV_HAAR_DO_CANNY_PRUNNING*/,
            cvSize( 40, 40) );

    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 );
    }

    //cvShowImage( "video:", img );
    cvSetImageROI(img, CvRect *r);

    IplImage *img2 = cvCreateImage(cvGetSize(img), 
                              img->depth, 
                               img->nChannels);

    cvSaveImage("Lakshmen.jpg",img2); 
}

Have a error saying this :

 Error  1   error C2664: 'cvSetImageROI' : cannot convert parameter 2 from 'CvRect *' to 'CvRect'   c:\users\hp\documents\visual studio 2010\projects\facedetect\facedetect\facedetect.cpp  67  1   facedetect

Want to save the region of interest into another image. Any corrections or improvements do tell me..


Solution

  • you need to pass a CvRect and not a CvRect*, so you do not need the pointer (*) before r. and since it is already a cvRect you should just write:

     cvSetImageROI(img, &r);