首先有看了我前面几篇的博文的话,应该懂了,我为啥要先从大的照片中识别出人脸区域,有了这个我们才能去截取出我们想要的人脸部分,才能为后面的人脸识别做基础。然后需要opencv3.4自己自带的模型文件,在我们安装好的opencv目录下有,这里就不分享了。
#include <iostream>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/objdetect.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
//string xmlPath = "D:\\vs 2013 code\\3-7face\\3-7face\\haarcascade_frontalface_default.xml";
string xmlPath = "haarcascade_frontalface_alt.xml";
void detectAndDisplay(Mat image);//xmlpath 字符串记录那个.xml文件的路径
int main(int argc, char**argv)
{
//以检测图片1.jpg为例
Mat image = imread("2.jpg");
CascadeClassifier a; //创建脸部对象
if (!a.load(xmlPath)) //如果读取文件不出错,则检测人脸
{
cout << "无法加载xml文件" << endl;
return 0;
}
detectAndDisplay(image);// 检测人脸
return 0;
}
void detectAndDisplay(Mat image)
{
CascadeClassifier ccf; //创建脸部对象
ccf.load(xmlPath); //导入opencv自带检测的文件
vector<Rect> faces;
Mat gray;
cvtColor(image, gray, CV_BGR2GRAY);
equalizeHist(gray, gray);
ccf.detectMultiScale(gray, faces, 1.1, 3, 0, Size(50, 50), Size(500, 500));
for (vector<Rect>::const_iterator iter = faces.begin(); iter != faces.end(); iter++)
{
rectangle(image, *iter, Scalar(0, 0, 255), 2, 8); //画出脸部矩形
}
Mat image1;
for (size_t i = 0; i<faces.size(); i++)
{
Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2);
image1 = image(Rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height));
}
imshow("1", image);
imshow("2", image1);
cvWaitKey(0);
}
这里是截取静态图片中的人脸区域,保存起来,相应的我上一篇文章有按p键就可以截取视频的图片,做一下简单的修改其实也就实现了视频中的人脸区域截取人脸图片。
由于没有保存好参考链接,没有引出,请见谅。