ภาพรวม
สาธิตการ ติดตามใบหน้า (Face Tracking) แบบ Real-time โดยใช้ Ellipse (วงรี) แทน Rectangle เพื่อให้ได้จุดศูนย์กลางที่แม่นยำกว่า สำหรับการติดตามตำแหน่ง
โค้ดตัวอย่าง 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++) {
// หาจุดศูนย์กลางใบหน้า
Point center(faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5);
// วาดวงรีล้อมใบหน้า
ellipse(video_stream, center, Size(faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar(255,0,255), 4);
// คำนวณและแสดงพิกัด
int horizontal = faces[i].x + faces[i].width*0.5;
int vertical = faces[i].y + faces[i].height*0.5;
cout << "Position of the face is: (" << horizontal << "," << vertical << ")" << endl;
}
imshow("Face Detection", video_stream);
if (waitKey(10) == 27) break;
}
return 0;
}
จุดสำคัญ
- ใช้
ellipse()แทนrectangle()เพื่อให้ได้ Center Point ชัดเจน - พิกัดศูนย์กลาง =
(x + width/2, y + height/2) - แสดงพิกัดทาง Console ทุกเฟรม
- กด ESC เพื่อออก
ผลลัพธ์
แสดงหน้าต่างวิดีโอพร้อมวงรีล้อมใบหน้า และพิมพ์พิกัดศูนย์กลางใบหน้าใน Console

