เราจะเรียนรู้วิธีครอปใบหน้าที่ตรวจพบใน OpenCV โดยต้องใช้เมทริกซ์หลายตัว วิธีที่เหมาะสมที่สุดคือใช้ Image Array ในโปรแกรมนี้ประกาศเมทริกซ์ภาพ 2 ตัวดังนี้:
Mat cropped_faces[4];– เก็บภาพที่ครอปแล้วMat faceROI[4];– กำหนดพื้นที่สนใจ (Region of Interest)
ในกระบวนการตรวจจับ โปรแกรมจะหาตำแหน่งใบหน้าและเก็บไว้ใน Vector ชื่อ faces ซึ่งสามารถเก็บหลายรายการได้
ใช้โค้ด 2 บรรทัดนี้เพื่อระบุตำแหน่งและครอปพื้นที่ใบหน้า:
faceROI[i] = image_with_humanface(faces[i]);cropped_faces[i] = faceROI[i];
บรรทัดแรก: ต้นไว้ตำแหน่ง Vector ที่มีใบหน้าในภาพ image_with_humanface และครอปเก็บไว้ใน faceROI[i]
บรรทัดที่สอง: ส่งภาพที่ครอปแล้วไปยังเมทริกซ์อีกตัวเพื่อแสดงผล
โปรแกรมครอปใบหน้าและแสดงในหน้าต่างแยกกัน
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp> // rectangle()
#include <opencv2/objdetect/objdetect.hpp> // Cascade Classifier
#include <string>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
Mat image_with_humanface;
Mat cropped_faces[3];
Mat faceROI[3];
image_with_humanface = imread("friends3.jpg");
namedWindow("Face1");
namedWindow("Face2");
namedWindow("Face3");
string trained_classifier_location = "C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";
CascadeClassifier faceDetector;
faceDetector.load(trained_classifier_location);
vector<Rect> faces;
vector<Rect> 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;
int y = faces[i].y;
int h = y + faces[i].height;
int w = x + faces[i].width;
rectangle(image_with_humanface, Point(x, y), Point(w, h),
Scalar(255, 0, 255), 2, 8, 0);
}
imshow("Face1", cropped_faces[0]);
imshow("Face2", cropped_faces[1]);
imshow("Face3", cropped_faces[2]);
waitKey(0);
return 0;
}
ผลลัพธ์

หมายเหตุ: ตำแหน่งไฟล์ XML Classifier (haarcascade_frontalface_alt.xml) อาจแตกต่างไปตามการติดตั้ง OpenCV ควรตรวจสอบพาธที่ถูกต้อง