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

วิธีตรวจจับใบหน้าในภาพนิ่ง (Still Image) ด้วย OpenCV C++


ภาพรวม

สาธิตการ ตรวจจับใบหน้า (Face Detection) จาก ภาพนิ่ง (Still Image) พื้นฐานสุดๆ โดยใช้ Haar Cascade Classifier

Syntax: detectMultiScale()

detectMultiScale(src, faces, scaleFactor, minNeighbors, flags, minSize)
  • src: Matrix ภาพต้นทาง (Grayscale แนะนำ)
  • faces: Vector<Rect> เก็บตำแหน่งใบหน้าที่เจอ
  • scaleFactor (1.1): อัตราลดขนาดต่อสเกล (1.1=แม่น, 1.2=เร็ว)
  • minNeighbors (3-4): ความน่าเชื่อถือ (มาก=น่าเชื่อถือ, น้อย=เร็ว)
  • flags (CASCADE_SCALE_IMAGE): ขยายภาพ
  • minSize (20x20, 30x30): ขนาดวัตถุขั้นต่ำ

โค้ดตัวอย่าง 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("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;
}

ผลลัพธ์

แสดงภาพพร้อมสี่เหลี่ยมม่วงล้อมใบหน้าทุกใบที่ตรวจจับได้

วิธีตรวจจับใบหน้าในภาพนิ่ง (Still Image) ด้วย OpenCV C++