1、识别一幅图片中的人脸个数,这里采用的是绝对路径,可自行修改
#include <cstdio>
#include <cstdlib>
#include <>
#include <vector>
#include <iostream>
#include <string>
#include <opencv2\>
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
//加载Haar特征检测分类器
CascadeClassifier cascade;
("D:\\Program Files\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt2.xml");
// 载入图像
const string pstrImageName = "E:\\";
Mat SrcImage = imread(pstrImageName, CV_LOAD_IMAGE_COLOR);
Mat GrayImage;
cvtColor(SrcImage, GrayImage, CV_BGR2GRAY);
//人脸识别与标记
if (())
cout << "未加载分类器" << endl;
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 } }
};
vector<cv::Rect> faces;
DWORD dwTimeBegin, dwTimeEnd;
dwTimeBegin = GetTickCount();
// 识别
(GrayImage, faces);
dwTimeEnd = GetTickCount();
cout << "人脸个数:" << () - ()
<< "识别用时:" << dwTimeEnd - dwTimeBegin << "ms\n";
// 标记
int n = 0;
for (vector<cv::Rect>::const_iterator i = (); i <(); i++, n++)
{
Point center;
int radius;
= cvRound((i->x + i->width * 0.5));
= cvRound((i->y + i->height * 0.5));
radius = cvRound((i->width + i->height) * 0.25);
circle(SrcImage, center, radius, FaceCirclecolors[n % 8], 2);
}
imshow("src", SrcImage);
waitKey();
}
2、从视频流中识别人脸
#include "opencv2/objdetect/"
#include "opencv2/highgui/"
#include "opencv2/imgproc/"
#include <iostream>
#include <>
using namespace std;
using namespace cv;
/** 全局变量 */
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
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 } }
};
/** @主函数 */
int main(int argc, const char** argv)
{
face_cascade.load("D:\\Program Files\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml");
if (face_cascade.empty())
cout << "face error loading" << endl;
VideoCapture capture(0);
Mat frame;
while (1)
{
capture >> frame;
if (())
cout << "error" << endl;
vector<cv::Rect> faces;
Mat GrayImage;
cvtColor(frame, GrayImage, CV_BGR2GRAY);
// 识别
face_cascade.detectMultiScale(GrayImage, faces);
// 标记
int n = 0;
for (vector<cv::Rect>::const_iterator i = (); i!=(); i++, n++)
{
Point center;
int radius;
= cvRound((i->x + i->width * 0.5));
= cvRound((i->y + i->height * 0.5));
radius = cvRound((i->width + i->height) * 0.25);
circle(frame, center, radius, FaceCirclecolors[n % 8], 2);
}
imshow("video", frame);
waitKey(10);
}
return 0;
}