基于OpenCV的人脸识别
OpenCV是个好东西啊,这个开源的CV库包含了许多函数库,比如模板匹配,边缘检测,面部识别。这一次要学习的是人脸识别。我们先从一幅图像的面部识别开始。
直接上代码,下面的代码是从多个网页中抠来的,如果您发现里面包含了你的代码,请您及时通知我,我可以删掉。
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
int main(int argc, const char** argv)
{
//create the cascade classifier object used for the face detection
CascadeClassifier face_cascade;
//use the haarcascade_frontalface_alt.xml library
face_cascade.load("haarcascade_frontalface_alt2.xml");
const char* imagename = "test3.jpeg";
//从文件中读入图像
Mat img = imread(imagename);
//如果读入图像失败
if (img.empty())
{
fprintf(stderr, "Can not load image %s\n", imagename);
return -1;
}
//setup image files used in the process
Mat grayscaleFrame;
//convert captured image to gray scale and equalize
cvtColor(img, grayscaleFrame, CV_BGR2GRAY);
equalizeHist(grayscaleFrame, grayscaleFrame);
//create a vector array to store the face found
std::vector<Rect> faces;
//find faces and store them in the vector array
face_cascade.detectMultiScale(grayscaleFrame, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_SCALE_IMAGE, Size(30, 30));
//draw a rectangle for all found faces in the vector array on the original image
for (int i = 0; i < faces.size(); i++)
{
Point pt1(faces[i].x + faces[i].width, faces[i].y + faces[i].height);
Point pt2(faces[i].x, faces[i].y);
rectangle(img, pt1, pt2, cvScalar(0, 255, 0, 0), 3, 8, 0);
}
//print the output
imshow("Face Dection, Results", img);
//pause for 33ms
waitKey();
return 0;
}
请注意:成功运行此段代码需要做一些准备工作,比如要将“haarcascade_frontalface_alt2.xml”文件放到工程目录下,而这个文件可以在”C:\OPENCV3.0\opencv\sources\data\haarcascades”找到。