基于opencv级联分类器对脸和眼睛进行检测

利用opencv级联分类器进行人脸检测 人脸以及眼睛

基于c++、opencv的人脸检测
1、创建分类器对象

CascadeClassifier face_cascade, eyes_cascade;

2、加载数据的路径
加载本地opencv文件夹自带的xml文件

string face_cascade_name = "D:\\opencv\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
string eyes_cascade_name = "D:\\opencv\\opencv\\sources\\data\\haarcascades\\haarcascade_eye_tree_eyeglasses.xml";

3、主函数操作

    //判断文件是否存在
    if (!face_cascade.load(face_cascade_name))
    {
        cout << "could not load face_cascade";
        return -1;
    }
    if (!eyes_cascade.load(eyes_cascade_name))
    {
        cout << "could not load eyes_cascade";
        return -1;
    }
    //打开摄像头
    cap.open(0);
    if (!cap.isOpened())
    {
        cout << "could not load camera";
        return -1;
    }
    while (1) {
        cap >> frame;
        if (frame.empty()) {
            break;
        }
        else {
            detectAndDisplay(frame);//调用检测方法
        }
        uchar c = waitKey(100);
        if (c == 27) {
            break;//esc退出
        }
    }
    cap.release();
    return 0;

4、检测方法

void detectAndDisplay(Mat frame) {
    vectorfaces;
    Mat frame_gray;

    cvtColor(frame, frame_gray, CV_BGR2GRAY);
    equalizeHist(frame_gray, frame_gray);
    face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0, Size(30, 30));
    for (size_t t = 0; t < faces.size(); t++) {
        rectangle(frame, faces[t], Scalar(0, 0, 255), 2, LINE_AA, 0);

        //在每张脸上检测眼睛
        Mat faceROI = frame_gray(faces[t]);
        vectoreyes;
        eyes_cascade.detectMultiScale(faceROI, eyes, 1.1, 2, 0, Size(30, 30));
        for (size_t i = 0; i < eyes.size(); i++)
        {
            Point center(faces[t].x + eyes[i].x + eyes[i].width * 0.5, faces[t].y + eyes[i].y + eyes[i].height * 0.5);
            int radius = cvRound((eyes[i].width + eyes[t].height) * 0.25);
            circle(frame, center, radius, Scalar(255, 0, 0), 2, LINE_AA, 0);
        }
    }
    imshow("face_cascade", frame);
}

你可能感兴趣的:(opencv,c++,计算机视觉)