Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีตรวจจับใบหน้าที่ใหญ่ที่สุดใน OpenCV ด้วย C++


ภาพรวม

สาธิตการตรวจจับ ใบหน้าที่ใหญ่ที่สุด (Largest Face) เพียงใบเดียวจากภาพนิ่ง โดยใช้ Flag CASCADE_FIND_BIGGEST_OBJECT และการเปรียบเทียบพื้นที่

โค้ดตัวอย่าง C++

#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;
    // ใช้ Flag ค้นหาเฉพาะวัตถุใหญ่ที่สุด
    faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_FIND_BIGGEST_OBJECT);
    
    Rect maxRect;  // เริ่มต้นขนาด 0
    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;
}

เทคนิคสำคัญ

  1. Flag CASCADE_FIND_BIGGEST_OBJECT: ทำให้ Classifier คืนเฉพาะใบหน้าที่ใหญ่ที่สุด (เร็วกว่า)
  2. Rect.maxRect: เก็บสี่เหลี่ยมที่มีพื้นที่มากที่สุด
  3. face[i].area(): คืนค่า width × height
  4. Mat faceROI = image(maxRect): Crop เฉพาะบริเวณใบหน้าที่ใหญ่ที่สุด

ผลลัพธ์

แสดงภาพพร้อมสี่เหลี่ยมม่วงล้อมเฉพาะใบหน้าที่ใหญ่ที่สุด

วิธีตรวจจับใบหน้าที่ใหญ่ที่สุดใน OpenCV ด้วย C++