(1)新建一个项目,选择“空项目”
(2)添加cpp文件
(3)Cpp文件中代码为
#include <opencv2\opencv.hpp>
using namespace cv;
static CvMemStorage* storage = NULL;
static CvHaarClassifierCascade* cascade = NULL;
const char* cascadePath = "haarcascade_frontalface_alt_tree.xml";//xml文件在安装的opencv文件里,需复制到项目文件中
int main()
{
CvCapture* cap = cvCreateCameraCapture(0);//初始化摄像头
//初始化视频人脸检测
IplImage* cameraImage = NULL;
storage = cvCreateMemStorage(0);
cascade = (CvHaarClassifierCascade*)cvLoad(cascadePath);
while ((cameraImage = cvQueryFrame(cap)) != NULL)
{
cvWaitKey(1);//不加读取不到图像
//图片灰度化
IplImage* grayImage = cvCreateImage(cvSize(cameraImage->width, cameraImage->height), 8, 1);
cvCvtColor(cameraImage, grayImage, CV_BGR2GRAY);
//人脸目标检测
cvClearMemStorage(storage);
CvSeq* objects = cvHaarDetectObjects(grayImage, cascade, storage, 1.1, 2, 0, cvSize(30, 30));
//人脸用方框绘出
for (int i = 0; i < (objects ? objects->total : 0); i++)
{
CvRect* rect = (CvRect*)cvGetSeqElem(objects, i);
cvRectangle(cameraImage, cvPoint(rect->x, rect->y),
cvPoint(rect->x + rect->width, rect->y + rect->height), cvScalar(255, 0.0));
}
cvShowImage("videofacedete", cameraImage);
}
return 0;
}
(4)F5运行结果为