Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách theo dõi mắt trong OpenCV C++


Giới thiệu

Sau khi phát hiện mắt, việc theo dõi (tracking) mắt là nhiệm vụ đơn giản. Ta dùng đường tròn bao quanh mắt được phát hiện, theo dõi tâm đường tròn đó chính là theo dõi tâm mắt.

Kỹ thuật

  • Khai báo 2 biến x_axis, y_axis lưu tọa độ tâm
  • Sau khi vẽ đường tròn quanh mắt, gán tọa độ tâm vào 2 biến này
  • In ra console để quan sát vị trí real-time

Chương trình hoàn chỉnh

#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() {
    int x_axis, y_axis;
    Mat frame;
    namedWindow("Detect");
    VideoCapture image(0);
    if (!image.isOpened()) {
        cout << "Không thể truy cập camera. Kiểm tra kết nối." << 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);

                x_axis = eyes[j].x;
                y_axis = eyes[j].y;
                cout << "Vị trí mắt: (" << x_axis << "," << y_axis << ")" << endl;
            }
        }
        imshow("Detect", frame);
        if (waitKey(30) == 27) break;
    }
    return 0;
}

Kết quả

Cửa sổ hiển thị video real-time với elip tím bao quanh mặt, đường tròn xanh dương bao quanh mắt. Console in ra tọa độ (x,y) của mắt được phát hiện.