vs2017 + opencv3.4.3 照片人脸检测

#include   
#include   
#include   
#include   
using namespace std;
int main()
{
	// 加载Haar特征检测分类器  
	// haarcascade_frontalface_alt.xml系OpenCV自带的分类器 下面是我机器上的文件路径  
	const char *pstrCascadeFileName = "D:\\opencv\\sources\\data\\haarcascades_cuda\\haarcascade_frontalface_alt.xml";
	//const char *pstrCascadeFileName = "haarcascade_frontalface_alt.xml";
	CvHaarClassifierCascade *pHaarCascade = NULL;
	pHaarCascade = (CvHaarClassifierCascade*)cvLoad(pstrCascadeFileName);

	// 载入图像  
	const char *pstrImageName = "timg.jpg";
	IplImage *pSrcImage = cvLoadImage(pstrImageName, CV_LOAD_IMAGE_UNCHANGED);

	IplImage *pGrayImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);
	cvCvtColor(pSrcImage, pGrayImage, CV_BGR2GRAY);

	// 人脸识别与标记  
	if (pHaarCascade != NULL)
	{
		CvScalar FaceCirclecolors[] =
		{
			{0, 0, 255},
			{0, 128, 255},
			{0, 255, 255},
			{0, 255, 0},
			{255, 128, 0},
			{255, 255, 0},
			{255, 0, 0},
			{255, 0, 255}
		};

		CvMemStorage *pcvMStorage = cvCreateMemStorage(0);
		cvClearMemStorage(pcvMStorage);
		// 识别  
		DWORD dwTimeBegin, dwTimeEnd;
		dwTimeBegin = GetTickCount();
		CvSeq *pcvSeqFaces = cvHaarDetectObjects(pGrayImage, pHaarCascade, pcvMStorage);
		dwTimeEnd = GetTickCount();

		printf("人脸个数: %d   识别用时: %d ms\n", pcvSeqFaces->total, dwTimeEnd - dwTimeBegin);

		// 标记  
		for (int i = 0; i < pcvSeqFaces->total; i++)
		{
			CvRect* r = (CvRect*)cvGetSeqElem(pcvSeqFaces, i);
			CvPoint center;
			int radius;
			center.x = cvRound((r->x + r->width * 0.5));
			center.y = cvRound((r->y + r->height * 0.5));
			radius = cvRound((r->width + r->height) * 0.25);
			cvCircle(pSrcImage, center, radius, FaceCirclecolors[i % 8], 2);
		}
		cvReleaseMemStorage(&pcvMStorage);
	}

	const char *pstrWindowsTitle = "人脸识别 (http://blog.csdn.net/MoreWindows)";
	cvNamedWindow(pstrWindowsTitle, CV_WINDOW_AUTOSIZE);
	cvShowImage(pstrWindowsTitle, pSrcImage);

	cvWaitKey(0);

	cvDestroyWindow(pstrWindowsTitle);
	cvReleaseImage(&pSrcImage);
	cvReleaseImage(&pGrayImage);
	return 0;
}

文章主要为自己记录,不对的地方欢迎交流。

关键点:

1、opencv3.4.3官方下载为X64位的,我的vs2017 community 是X86的,所以需要用cmake 对opencv的\sources\文件夹重新编译(注意勾选world选项),有这个一个opencv_world343d.dll、opencv_world343d.lib库文件即可,头文件沿用原来include。

2、 cvLoad加载分类器需要调用 \opencv\sources\data\haarcascades_cuda这个文件夹下的XML文件就不会报错了。参考文章https://blog.csdn.net/H1250161943/article/details/50301831?locationNum=2

3.遇到detectMultiScale报错,很有可能是haarcascade_frontalface_alt2.xml文件加载失败,参考文章https://blog.csdn.net/cqltbe131421/article/details/73608975

4、亲测好用,但是不太准,还要训练。

vs2017 + opencv3.4.3 照片人脸检测_第1张图片

你可能感兴趣的:(opencv)