Giới thiệu
Để cắt các khuôn mặt phát hiện được, dùng mảng Mat lưu từng khuôn mặt cắt ra: faceROI[i] = image(faces[i]) rồi copy sang cropped_faces[i] để hiển thị riêng.
Chương trình cắt và hiển thị 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("friends3.jpg");
Mat cropped_faces[3], faceROI[3];
namedWindow("Face1"); namedWindow("Face2"); namedWindow("Face3");
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++) {
faceROI[i] = image_with_humanface(faces[i]);
cropped_faces[i] = faceROI[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("Face1", cropped_faces[0]);
imshow("Face2", cropped_faces[1]);
imshow("Face3", cropped_faces[2]);
waitKey(0);
return 0;
}
Kết quả
Cửa sổ chính hiển thị ảnh gốc với các hình chữ nhật tím quanh mặt. 3 cửa sổ riêng hiển thị từng khuôn mặt được cắt ra.