代码中的模型是训练好的:haarcascade_frontalface_default.xml
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <iostream>
using namespace cv;
using namespace std;
/// 人脸检测 //
void main() {
VideoCapture cap(0);//无外接摄像头用0
Mat img;
while (true) {
cap.read(img);
CascadeClassifier faceCascade;/*用于对象检测的级联分类器类*/
faceCascade.load("Resources/haarcascade_frontalface_default.xml");//从文件加载分类器(已经训练好的模型)
if (faceCascade.empty()) { cout << "XML file not loaded" << endl; }//判断文件是否调用,存在
//创建矩形向量
vector<Rect> faces;
//人脸级联点检测多尺度法
faceCascade.detectMultiScale(img, faces, 1.1, 10);//在输入图像中检测不同大小的对象。检测到的对象将以矩形列表的形式返回。img/*输入*/, faces/*输出*/, 1.1/*比例因子*/, 10/*最小邻居*/
for (int i = 0; i < faces.size(); i++) {
rectangle(img, faces[i].tl()/*左上角*/, faces[i].br()/*右下角*/, Scalar(255, 0, 255), 3);//绘制矩形
}
imshow("Image", img);
waitKey(1);
}
}