简体   繁体   中英

How to extract face from an image?

I have successfully detected a face out of an image having other things in background using OpenCv . Now I need to extract just the detected part (ie face) and convert it into some image format like jpeg or gif to make a face database to use for my neural net training.

How can I do this?

Once you detect the faces, you get opposite corners of a rectangle, which is used to draw rectangles around the face.

Now you can set image ROI ( Region of Interest) , crop the ROI and save it as another image.

/* After detecting the rectangle points, Do as follows */     
/* sets the Region of Interest
   Note that the rectangle area has to be __INSIDE__ the image */
cvSetImageROI(img1, cvRect(10, 15, 150, 250));

/* create destination image
   Note that cvGetSize will return the width and the height of ROI */
IplImage *img2 = cvCreateImage(cvGetSize(img1),
                               img1->depth,
                               img1->nChannels);

/* copy subimage */
cvCopy(img1, img2, NULL);

/* always reset the Region of Interest */
cvResetImageROI(img1);

Above code is taken from http://nashruddin.com/OpenCV_Region_of_Interest_(ROI )

Further cvSaveImage function can be used to save image to a file.

try this:

for(i=0;i<(pFaceRectSeq?pFaceRectSeq->total:0);i++)
{
CvRect* r=(CvRect*)cvGetSeqElem(pFaceRectSeq,i);
int width=r->width;
int height=r->height;   
cvSetImageROI(pInpImg,*r);
IplImage* pCropImg=cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,3);
cvCopy(pInpImg,pCropImg,NULL);
cvShowImage("Cropped Window",pCropImg);
cvWaitKey(0);
cvResetImageROI(pInpImg);
cvReleaseImage(&pCropImg);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM