代码如下:
#include "stdafx.h"
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
Mat img;
Mat grayscaleFrame;
CascadeClassifier face_cascade;
face_cascade.load("haarcascade_frontalface_alt2.xml");//相对路径,将xml文件放在相应文件里
VideoCapture cam(0);
if (!cam.isOpened()) exit(0);
while (true)
{
cam >> img;
cvtColor(img, grayscaleFrame, CV_BGR2GRAY);
equalizeHist(grayscaleFrame,grayscaleFrame);
std::vector<Rect> faces;
face_cascade.detectMultiScale(grayscaleFrame,faces, 1.1, 3, 0,Size(20, 20));
for (int i = 0; i < faces.size(); i++)
{
Point pt1(faces[i].x + faces[i].width, faces[i].y + faces[i].height);
Point pt2(faces[i].x, faces[i].y);
rectangle(img, pt1, pt2, cvScalar(0,255, 255, 0), 2, 8, 0);
}
imshow("Camera", img);
waitKey(10);
}
return 0;
}
//函数介绍
/*
CV_WRAPVideoCapture(int index);
@paramindex = camera_id + domain_offset (CAP_*). id of the video capturing device toopen. If there is a single
cameraconnected, just pass 0. Advanced Usage: to open Camera 1 using the MS MediaFoundation API: index = 1 + CAP_MSMF
*/
源码下载:http://download.csdn.net/detail/cracent/9492683