Giới thiệu
Phát hiện chỉ khuôn mặt lớn nhất bằng cách dùng cờ CASCADE_FIND_BIGGEST_OBJECT trong detectMultiScale hoặc tự lọc qua diện tích faces[i].area().
Chương trình phát hiện khuôn mặt lớn nhấ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;
// Cách 1: Dùng flag CASCADE_FIND_BIGGEST_OBJECT
faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_FIND_BIGGEST_OBJECT);
// Cách 2: Tự lọc (demo trong code gốc)
Rect maxRect;
for (int i = 0; i < faces.size(); i++) {
if (faces[i].area() > maxRect.area())
maxRect = faces[i];
}
for (size_t i = 0; i < faces.size(); i++) {
Mat faceROI = image_with_humanface(maxRect);
int x = maxRect.x, y = maxRect.y;
int h = y + maxRect.height, w = x + maxRect.width;
rectangle(image_with_humanface, Point(x, y), Point(w, h), Scalar(255, 0, 255), 3);
}
imshow("Face Detection", image_with_humanface);
waitKey(0);
return 0;
}
Kết quả
Ảnh hiển thị hình chữ nhật tím dày bao quanh khuôn mặt lớn nhất được phát hiện.