ภาพรวม
สาธิตการ ตรวจจับใบหน้า (Face Detection) แบบ Real-time จากกล้องเว็บแคม โดยใช้ Haar Cascade Classifier
หลักการทำงาน
- ใช้
VideoCapture(0)จับภาพจากกล้อง Default - แต่ละเฟรม ใช้
detectMultiScale()หาใบหน้า - วาด
rectangle()ล้อมรอบใบหน้าที่เจอ - แสดงผลด้วย
imshow()
โค้ดตัวอย่าง 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 video_stream;
VideoCapture real_time(0);
namedWindow("Face Detection");
string trained_classifier_location = "haarcascade_frontalface_alt.xml";
CascadeClassifier faceDetector;
faceDetector.load(trained_classifier_location);
vector<Rect> faces;
while (true) {
faceDetector.detectMultiScale(video_stream, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(30,30));
real_time.read(video_stream);
for (int i = 0; i < faces.size(); i++) {
Mat faceROI = video_stream(faces[i]);
int x = faces[i].x;
int y = faces[i].y;
int h = y + faces[i].height;
int w = x + faces[i].width;
rectangle(video_stream, Point(x, y), Point(w, h), Scalar(255,0,255), 2);
}
imshow("Face Detection", video_stream);
if (waitKey(10) == 27) break;
}
return 0;
}
คำอธิบาย detectMultiScale Parameters
detectMultiScale(src, faces, scaleFactor, minNeighbors, flags, minSize)
- scaleFactor=1.1: ลดขนาดภาพทีละ 10% ต่อสเกล
- minNeighbors=4: ต้องมี Neighbors 4 ตัวจึงยืนยันว่าเป็นใบหน้า
- flags=CASCADE_SCALE_IMAGE: ขยายภาพ ไม่ขยาย Classifier
- minSize=30x30: ขนาดใบหน้าขั้นต่ำ
ผลลัพธ์
แสดงหน้าต่างวิดีโอพร้อมสี่เหลี่ยมม่วงล้อมใบหน้าทุกใบที่ตรวจจับได้
