C++ opencv4.1实现人脸检测

C++ opencv4.1实现人脸检测

本文采用opencv4.1中haarcascades文件下存放的Haar特征的级联分类器(Cascade Classfier)进行人脸检测。
代码实现:

#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include 
#include 

using namespace std;
using namespace cv;

void detectAndDisplay(Mat frame);
string face_cascade_name = "C:/Opencv410/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";   //加载分类器
string eyes_cascade_name = "C:/Opencv410/opencv/sources/data/haarcascades/haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;      //人脸检测的类
CascadeClassifier eyes_cascade;
string window_name = "Capture - Face detection";
RNG rng(12345);

int main(int argc, const char** argv)
{
    Mat frame;
    //-- 1. 加载级联分类器文件
    if (!face_cascade.load(face_cascade_name)) { cout<<"--(!)Error loading"<> frame;
              //-- 3. 对当前帧使用分类器进行检测
              if (!frame.empty())
                    detectAndDisplay(frame);
              else
                    cout << " --(!) No captured frame -- Break!" << endl; break;
               int c = waitKey(10);
               if ((char)c == 'q') { break; }
               /*char key = (char) waitKey();
               if (key == 27 || key == 'q' || key == 'Q')
                   break;*/
        }
    }
    return 0;
}

void detectAndDisplay(Mat frame)
{
      vector faces;
      Mat frame_gray;
      cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
      equalizeHist(frame_gray, frame_gray);    //直方图均衡化
      //-- 多尺寸检测人脸
      face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 , Size(30, 30));
      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(frame, center, Size(faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar(255, 0, 255), 4, 8, 0);
           Mat faceROI = frame_gray(faces[i]);
           vector eyes;

          //-- 在每张人脸上检测双眼
          eyes_cascade.detectMultiScale(faceROI, eyes, 1.1, 2, 0 , Size(30, 30));
          for (int j = 0; j < eyes.size(); j++)
          {
                Point center(faces[i].x + eyes[j].x + eyes[j].width*0.5, faces[i].y + eyes[j].y + eyes[j].height*0.5);
                int radius = cvRound((eyes[j].width + eyes[i].height)*0.25);
                circle(frame, center, radius, Scalar(255, 0, 0), 4, 8, 0);
          }

     }
     imshow(window_name, frame);
}

你可能感兴趣的:(计算机视觉)