上一篇介绍了cascade分类器的训练,这里给出训练好的xml文件进行人脸检测的代码(由于眼睛发炎不能长时间看电脑屏幕,以后补详细介绍)
#include <iostream> #include <opencv2\core\core.hpp> #include <opencv2\highgui\highgui.hpp> #include <opencv2\imgproc\imgproc.hpp> #include <opencv2\objdetect\objdetect.hpp> using namespace std; using namespace cv; //定义全局变量 string face_cascade_name = "haarcascade_frontalface_alt.xml"; //string face_cascade_name = "haarcascade_frontalface_default.xml"; string face_detect_txt = "face"; CascadeClassifier face_cascade; //创建分类器对象 int main() { Mat srcImage, grayImage; srcImage = imread("bigBang.jpg"); //判断图像是否加载成功 if (srcImage.empty()) { cout << "图像加载失败..."; return -1; } //加载级联分类器 if (!face_cascade.load(face_cascade_name)) { cout << "分类文件加载失败..."; return -1; } //定义存放检测到人脸的矢量 vector<Rect> faces; cvtColor(srcImage, grayImage, COLOR_BGR2GRAY); //转换为灰度图 equalizeHist(grayImage, grayImage); //直方图均衡化 //多尺寸检测人脸 face_cascade.detectMultiScale(grayImage, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100)); //以矩形绘制检测到的人脸 for (int i = 0; i < faces.size(); i++) { rectangle(srcImage, Point(faces[i].x, faces[i].y), Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height), Scalar(0, 0, 255), 2, 8, 0); putText(srcImage, face_detect_txt, Point(faces[i].x, faces[i].y - 2), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(255, 0, 0), 2, 8, false); } imshow("face", srcImage); waitKey(0); return 0; }运行结果