Giới thiệu
Phát hiện khuôn mặt từ ảnh tĩnh dùng hàm detectMultiScale() với các tham số:
- Source Matrix: Ma trận ảnh đầu vào
- Vector: Vector
lưu vị trí khuôn mặt - searchScaleFactor: 1.1 (tỷ lệ co giãn tìm kiếm)
- minNeighbours: 4 (độ tin cậy, càng cao càng chắc nhưng chậm hơn)
- flags: CASCADE_SCALE_IMAGE (tìm nhiều mặt) hoặc CASCADE_FIND_BIGGEST_OBJECT (chỉ mặt lớn nhất)
- minFeatureSize: Size(20,20) kích thước mặt nhỏ nhất
Chương trình phát hiện khuôn mặt ảnh tĩnh
#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("friends.jpg");
namedWindow("Face Detection");
string trained_classifier_location = "haarcascade_frontalface_alt.xml";
CascadeClassifier faceDetector;
faceDetector.load(trained_classifier_location);
vector<Rect> faces, boundary;
faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(20, 20));
for (size_t i = 0; i < faces.size(); i++) {
Mat faceROI = image_with_humanface(faces[i]);
int x = faces[i].x, y = faces[i].y;
int h = y + faces[i].height, w = x + faces[i].width;
rectangle(image_with_humanface, Point(x, y), Point(w, h), Scalar(255, 0, 255), 2);
}
imshow("Face Detection", image_with_humanface);
waitKey(0);
return 0;
}
Kết quả
Ảnh hiển thị các hình chữ nhật tím bao quanh tất cả khuôn mặt được phát hiện.