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);               
        cvResetImageROI(Src);       
        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);
        cvZero(roi);cvZero(res);   
       
        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);            

}