代码:
#include<opencv2/opencv.hpp>
#include<opencv2/core/core.hpp> // 核心组件
#include<opencv2/objdetect/objdetect.hpp>
#include<opencv2/highgui/highgui.hpp> // GUI
#include<opencv2/imgproc/imgproc.hpp> // 图像处理
using namespace cv;
using namespace std;
CascadeClassifier faceCascade;
//训练文件路径
//Note:路径需要用双右下划线,即"\\"
string xmlPath = "D:\\Opencv\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt2.xml";
int main()
{
faceCascade.load(xmlPath);
if (!faceCascade.load(xmlPath)) //加载训练文件
{
cout << "不能加载指定的xml文件" << endl;
return -1;
}
VideoCapture capture;
capture.open(0);//打开摄像头 注意这个地方的参数
if (!capture.isOpened()) {
cout << "open camera failed." << endl;
return -1;
}
Mat img, imgGray;
vector<Rect>faces;
//cout << 111 << endl;
while (1) {
capture >> img;//读取图像至img
if (img.empty()) {
continue;
}
if (img.channels() == 3) {
cvtColor(img, imgGray, CV_RGB2GRAY);
}
else {
imgGray = img;
}
faceCascade.detectMultiScale(imgGray,faces, 1.2, 6, 0, Size(0, 0));//检测人脸
if (faces.size() > 0)
{
for (int i = 0; i < faces.size(); i++)
{
rectangle(img, Point(faces[i].x, faces[i].y), Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height), Scalar(0, 255, 0), 1, 8);
}
}
imshow("CamerFace", img); // 显示
if (waitKey(1) > 0) // delay ms 等待按键退出
{
break;
}
}
return 0;
}