Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách theo dõi vị trí khuôn mặt trong OpenCV C++


Giới thiệu

Để theo dõi vị trí khuôn mặt chính xác, dùng elip vì elip có tâm xác định. Tâm elip = tâm khuôn mặt. Chương trình xử lý ảnh tĩnh (person.jpg).

Chương trình theo dõi vị trí khuôn mặt

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <string>
using namespace std;
using namespace cv;

int main(int argc, char** argv) {
    Mat image_with_humanface = imread("person.jpg");
    namedWindow("Face Detection");
    string trained_classifier_location = "haarcascade_frontalface_alt.xml";
    CascadeClassifier faceDetector;
    faceDetector.load(trained_classifier_location);
    vector<Rect> faces;

    faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(20, 20));

    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(image_with_humanface, center, Size(faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar(255, 0, 255), 4);
        int horizontal = faces[i].x + faces[i].width*0.5;
        int vertical = faces[i].y + faces[i].height*0.5;
        cout << "Vị trí khuôn mặt tại (x,y)= (" << horizontal << "," << vertical << ")" << endl;
    }
    imshow("Face Detection", image_with_humanface);
    waitKey(0);
    return 0;
}

Kết quả

Ảnh hiển thị elip tím bao quanh khuôn mặt lớn nhất, console in tọa độ tâm khuôn mặt.