基于opencv3的人脸检测

目前opencv3中已经有人脸检测的类了,只要调用函数库的类就行

该程序需要两个xml文件,分别是haarcascade_frontalface_alt.xml和haarcascade_eye_tree_eyeglasses.xml,它们分别是已经通过了大量训练且能检测出人脸和眼睛了,只要调用即可。

#include"opencv2/objdetect/objdetect.hpp"
#include"opencv2/highgui/highgui.hpp"
#include"opencv2/imgproc/imgproc.hpp"
#include"opencv2/core/core.hpp"
#include"iostream"
using namespace std;
using namespace cv;

void detection(Mat frame);
String face_cascade_name = "haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;

int main()
{
    if (!face_cascade.load(face_cascade_name))
        cerr << "Loading haarcascade_frontalface_alt.xml error"<if (!eyes_cascade.load(eyes_cascade_name))
        cerr << "Loading haarcascade_eye_tree_eyeglasses.xml error" << endl;

    VideoCapture capture(0);
    Mat frame;
    while (1)
    {
        capture >> frame;
        if (!frame.data)
            cerr << "Opening capture error!" << endl;
        detection(frame);
        waitKey(15);
    }
    return 0;
}

void detection(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 | 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));//人脸检测
    for (int i = 0; i < faces.size(); i++)
    {
        //用椭圆圈出脸
        Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2);
        ellipse(frame, center, Size(faces[i].width / 2, faces[i].height / 2), 0, 0, 360, Scalar(255, 0, 255), 2, 8, 0);
        //用圆圈出眼睛
        Mat face_roi = frame_gray(faces[i]);
        vector eyes;
        eyes_cascade.detectMultiScale(face_roi, eyes, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));//在脸中检测眼睛
        for (int j = 0; j < eyes.size(); j++)
        {
            Point eye_center(faces[i].x + eyes[j].x + eyes[j].width / 2, faces[i].y + eyes[j].y + eyes[j].height / 2);
            int radius = cvRound((eyes[j].width + eyes[j].height)*0.25);
            circle(frame, eye_center, radius, Scalar(255, 0, 0), 3, 8, 0);
        }
    }
    //-- 显示最终效果图
    imshow("picture", frame);
}

你可能感兴趣的:(opencv)