分类器CascadeClassifier是Opencv的一个类,主要有两个成员函数:
一个是Load()函数,主要用来读取分类使用的文本,Opencv自带一套使用的人脸及特征检测的文本。
还有一个是void detectMultiScale( InputArray image,
CV_OUT std::vector
double scaleFactor = 1.1,
int minNeighbors = 3, int flags = 0,
Size minSize = Size(),
Size maxSize = Size() );
此函数用于检测特征,以下为主要参数说明
参数1:输入图片
参数2:输出找到的特征的外接矩形数组,如vector
参数3:图片放缩比例,一般默认
参数4:相邻特征矩形最小的像素差
下面程序中,首先对人脸进行检测,检测到人脸特征后对于人脸部位,进一步检测眼睛
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
//主函数
int main()
{
Mat img;
namedWindow("detected");
img = imread("2.jpg");
vector<Rect>faces;
CascadeClassifier classifier_face;
classifier_face.load("haarcascade_frontalface_default.xml");
classifier_face.detectMultiScale(img,faces,1.1,3);
vector<Rect>eyes;
CascadeClassifier classifier_eye;
classifier_eye.load("haarcascade_eye.xml");
if (faces.size())
{
for (int i = 0; i < faces.size(); i++)
{
cv::rectangle(img, faces[i], Scalar(255, 0, 0));
Mat faceimg = img(faces[i]);
classifier_eye.detectMultiScale(faceimg, eyes, 1.1, 3);
if(eyes.size())
{
for (int j = 0; j < eyes.size(); j++)
{
Rect tmpRect;
tmpRect.x = faces[i].x + eyes[j].x;
tmpRect.y = faces[i].y + eyes[j].y;
tmpRect.width = eyes[j].width;
tmpRect.height = eyes[j].height;
cv::rectangle(img, tmpRect, Scalar(0, 255, 0));
}
}
}
imshow("detected", img);
waitKey();
}
else
cout << "Not face detected";
}