如何从图像中提取人脸

How to extract face from an image?

本文关键字:提取 图像      更新时间:2023-10-16

我使用OpenCv成功地从背景中有其他东西的图像中检测到了一张脸。现在,我只需要提取检测到的部分(即人脸),并将其转换为jpeggif等图像格式,以创建一个人脸数据库,用于我的神经网络训练。

我该怎么做?

一旦检测到人脸,就会得到矩形的对角,用于在人脸周围绘制矩形。

现在,您可以设置图像ROI(感兴趣区域),裁剪ROI并将其保存为另一张图像。

/* 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);

以上代码取自http://nashruddin.com/OpenCV_Region_of_Interest_(ROI)

此外,还可以使用cvSaveImage功能将图像保存到文件中。

试试这个:

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