Giới thiệu
Tương tự phát hiện khuôn mặt, nhưng dùng elip (ellipse) thay vì hình chữ nhật để bao quanh mặt. Tâm elip chính là tâm khuôn mặt, giúp theo dõi vị trí chính xác hơn. Thêm lệnh cout in tọa độ ra console.
Chương trình theo dõi khuôn mặt real-time
#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 video_stream;
VideoCapture real_time(0);
namedWindow("Face Detection");
string trained_classifier_location = "haarcascade_frontalface_alt.xml";
CascadeClassifier faceDetector;
faceDetector.load(trained_classifier_location);
vector<Rect> faces;
while (true) {
faceDetector.detectMultiScale(video_stream, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(30, 30));
real_time.read(video_stream);
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(video_stream, 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; // Sửa: height thay vì width
cout << "Vị trí khuôn mặt: (" << horizontal << "," << vertical << ")" << endl;
}
imshow("Face Detection", video_stream);
if (waitKey(10) == 27) break;
}
return 0;
}
Kết quả
Video real-time với elip tím bao quanh khuôn mặt, console in liên tục tọa độ tâm khuôn mặt (x,y).