人脸检测
程序员文章站
2022-07-12 20:17:44
...
配置环境
https://blog.csdn.net/ccnuacmhdu/article/details/79757658
人脸检测
代码参考博主网站:https://blog.csdn.net/real_myth/article/details/52771154
/*
本程序实现人脸检测,
顺便学习了一下sprinf,实现批量操作图像
*/
#include "opencv2/core/core.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
using namespace cv;
string face_cascade_name = "haarcascade_frontalface_alt.xml";
//该文件存在于OpenCV安装目录下的\sources\data\haarcascades内,需要将该xml文件复制到当前工程目录下
CascadeClassifier face_cascade;
void detectAndDisplay(Mat frame);
int main(int argc, char** argv) {
char fileName[100];
Mat image;
for (int i = 1; i <= 4; i++) {
sprintf(fileName, "F:/人脸识别/face_detect/face_detect/image/%d.jpg", i);
image = imread(fileName);//导入图片
if (!face_cascade.load(face_cascade_name)) {
printf("级联分类器错误,可能未找到文件,拷贝该文件到工程目录下!\n");
return -1;
}
detectAndDisplay(image); //调用人脸检测函数
waitKey();//暂停显示一下
}
return 0;
}
void detectAndDisplay(Mat face) {
std::vector<Rect> faces;
Mat face_gray;
cvtColor(face, face_gray, CV_BGR2GRAY); //rgb类型转换为灰度类型
equalizeHist(face_gray, face_gray); //直方图均衡化
face_cascade.detectMultiScale(face_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(1, 1));
for (int i = 0; i < faces.size(); i++) {
Point center(faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5);
ellipse(face, center, Size(faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar(255, 0, 0), 2, 7, 0);
}
imshow("人脸检测", face);
}
\
注意上面代码中的路径信息:
sprintf(fileName, “F:/人脸识别/face_detect/face_detect/image/%d.jpg”, i);
如果不小心改变了项目工程的路径,这里一定要修改一下!!!