ภาพรวม
สาธิตวิธี ตรวจจับตา (Eye Detection) แบบพื้นฐาน โดยใช้ Haar Cascade Classifier haarcascade_eye.xml
Header ที่จำเป็น
<iostream>- Input/Output มาตรฐาน<opencv2/highgui/highgui.hpp>- GUI, โหลด/แสดงภาพ<opencv2/imgproc/imgproc.hpp>- Image Processing<opencv2/objdetect/objdetect.hpp>- Object Detection (Cascade Classifier)
โค้ดตัวอย่าง C++
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
using namespace cv;
using namespace std;
int main() {
Mat frame;
namedWindow("Detect");
VideoCapture image(0);
if (!image.isOpened()) {
cout << "Couldn't load video from source." << endl;
system("pause");
return 0;
}
image.set(CAP_PROP_FRAME_HEIGHT, 480);
image.set(CAP_PROP_FRAME_WIDTH, 640);
CascadeClassifier face_cascade, eyes_cascade;
face_cascade.load("haarcascade_frontalface_alt.xml");
eyes_cascade.load("haarcascade_eye.xml");
while (true) {
bool temp = image.read(frame);
vector<Rect> faces;
face_cascade.detectMultiScale(frame, faces, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(100,100));
for (int i = 0; i < faces.size(); i++) {
Point center(faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5);
ellipse(frame, center, Size(faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar(255,0,255), 4);
Mat faceROI = frame(faces[i]);
vector<Rect> eyes;
eyes_cascade.detectMultiScale(faceROI, eyes, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(5,5));
for (size_t j = 0; j < eyes.size(); j++) {
Point eyeCenter(faces[i].x + eyes[j].x + eyes[j].width*0.5,
faces[i].y + eyes[j].y + eyes[j].height*0.5);
int radius = cvRound((eyes[j].width + eyes[j].height) * 0.25);
circle(frame, eyeCenter, radius, Scalar(255,0,0), 4);
}
}
imshow("Detect", frame);
if (waitKey(30) == 27) break;
}
return 0;
}
คำอธิบายพารามิเตอร์ detectMultiScale
- scaleFactor (1.1): อัตราการขยายภาพในแต่ละสเกล (1.1 = ช้าแต่แม่น, 1.2 = เร็วแต่พลาดง่าย)
- minNeighbors (2-4): ความเชื่อมั่นของการตรวจจับ (ค่ามาก = น่าเชื่อถือแต่ช้า)
- flags (CASCADE_SCALE_IMAGE): ขยายภาพแทนการขยาย Classifier
- minSize (20x20, 30x30): ขนาดขั้นต่ำของวัตถุที่ตรวจจับได้
ผลลัพธ์
แสดงหน้าต่างวิดีโอพร้อมวงรีล้อมใบหน้า และวงกลมล้อมตาทั้งสองข้าง
