项目运行涉及到opencv库,以及haarcascade_frontalface_default.xml和haarcascade_eye_tree_eyeglasses.xml。qt配置opencv可见先前文章,另外这两份OpenCV 中用于眼睛检测的级联分类器xml文件,是我在网上下载的。
把要使用到的文件都放到当前工程目录下:
相关代码:
cpp
#include <opencv2/imgcodecs.hpp>
#include <opencv2/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/core/hal/interface.h>
#include <opencv2/features2d/hal/interface.h>
#include <opencv2/imgproc/hal/interface.h>
#include <opencv2/objdetect.hpp>
QString imgPath = "D:\\Qt\\File\\open_test\\zyh.jpg";
cv::Mat imgMat = cv::imread(imgPath.toStdString());
//脸部识别
cv::CascadeClassifier faceCascade;
faceCascade.load("D:\\Qt\\File\\open_test\\opencv\\haarcascades\\haarcascade_frontalface_default.xml");
if(faceCascade.empty())
std::cout<< "face XML file not loaded"<<std::endl;
std::vector<cv::Rect> faces;
faceCascade.detectMultiScale(imgMat, faces, 1.1, 10);
for(int i=0; i<faces.size(); i++){
cv::rectangle(imgMat, faces[i].tl(), faces[i].br(), cv::Scalar(255,0,255),3);
}
//眼部识别
cv::CascadeClassifier eyeCascade;
eyeCascade.load("D:\\Qt\\File\\open_test\\opencv\\haarcascades\\haarcascade_eye_tree_eyeglasses.xml");
if(eyeCascade.empty())
std::cout<< "eye XML file not loaded"<<std::endl;
std::vector<cv::Rect> eyes;
eyeCascade.detectMultiScale(imgMat, eyes, 1.1, 10);
for(int i=0; i<eyes.size(); i++){
cv::rectangle(imgMat, eyes[i].tl(), eyes[i].br(), cv::Scalar(255,0,0),1);
}
cv::imshow("Image", imgMat);