人脸检测的测试程序(视频和摄像头)

时间:2022-08-16 19:38:39

人脸检测的测试程序(视频和摄像头),仅供测试使用。

#include"stdafx.h"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/opencv.hpp"

#include <vector>
#include <cstdio>
#ifdef _DEBUG
#pragma comment(lib,"lib/opencv_core249d.lib")
#pragma comment(lib,"lib/opencv_imgproc249d.lib")
#pragma comment(lib,"lib/opencv_highgui249d.lib")
#pragma comment(lib,"lib/opencv_objdetect249d.lib")
#pragma comment(lib,"lib/opencv_ml249d.lib")
#else
#pragma comment(lib,"lib/opencv_core249")
#pragma comment(lib,"lib/opencv_imgproc249")
#pragma comment(lib,"lib/opencv_highgui249")
#pragma comment(lib,"lib/opencv_objdetect249")
#pragma comment(lib,"lib/opencv_ml249")
#endif
using namespace std;
using namespace cv;

int main()
{
Mat grayImage, dstImage;
// 定义7种颜色,用于标记人脸
Scalar colors[] =
{
// 红橙黄绿青蓝紫
CV_RGB(255, 0, 0),
CV_RGB(255, 97, 0),
CV_RGB(255, 255, 0),
CV_RGB(0, 255, 0),
CV_RGB(0, 255, 255),
CV_RGB(0, 0, 255),
CV_RGB(160, 32, 240)
};
// 【1】加载分类器
CascadeClassifier cascade;
cascade.load("haarcascade_frontalface_alt2.xml");

CvCapture* capture = 0;
//capture = cvCaptureFromAVI("vid.wmv");
capture = cvCaptureFromCAM(0);
if (!capture)
{
cerr << "cannot initialize video!" << endl;
return -1;
}
Mat Image, current_shape;
for (;;){
Image = cvQueryFrame(capture);
flip(Image, Image, 1);//使用摄像头时需要翻转图像
cvtColor(Image, grayImage, CV_BGR2GRAY); // 生成灰度图,提高检测效率
// 【3】检测
vector<Rect> rect;
cascade.detectMultiScale(grayImage, rect, 1.1, 3, 0); // 分类器对象调用

printf("检测到人脸个数:%d\n", rect.size());

// 【4】标记--在脸部画圆
for (int i = 0; i < rect.size(); i++)
{
Point center;
int radius;
center.x = cvRound((rect[i].x + rect[i].width * 0.5));
center.y = cvRound((rect[i].y + rect[i].height * 0.5));

radius = cvRound((rect[i].width + rect[i].height) * 0.25);
circle(Image, center, radius, colors[i % 7], 2);
}
namedWindow("1", CV_WINDOW_AUTOSIZE);
imshow("1", Image);
waitKey(3);
}

return 0;
}
cascade.detectMultiScale(smallImg, faces,1.1, 3, 0
//|CV_HAAR_FIND_BIGGEST_OBJECT
//|CV_HAAR_DO_ROUGH_SEARCH
| CV_HAAR_SCALE_IMAGE
,Size(30, 30));
detectMultiScale函数中smallImg表示的是要检测的输入图像为smallImg,faces表示检测到的人脸目标序列,1.1表示每次图像尺寸减小的比例为1.1,3表示每一个候选矩形需要记录3个邻居,CV_HAAR_SCALE_IMAGE表示使用haar特征,Size(30, 30)为目标的最小最大尺寸。