Giới thiệu
Sử dụng haarcascade_eye.xml trong thư mục opencv/sources/data/haarcascades để phát hiện mắt. Cần các header: iostream, highgui, imgproc, objdetect.
Chương trình phát hiện mắt cơ bản
#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 << "Không thể tải video từ camera." << 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;
}
Kết quả
Video real-time hiển thị elip tím quanh khuôn mặt và đường tròn xanh dương quanh mắt được phát hiện.