Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีติดตามตำแหน่งใบหน้าใน OpenCV ด้วย C++


ภาพรวม

สาธิตการ ติดตามตำแหน่งใบหน้า (Face Position Tracking) จากภาพนิ่ง (Still Image) โดยใช้ Ellipse เพื่อหาจุดศูนย์กลางที่แม่นยำ

โค้ดตัวอย่าง 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 image_with_humanface = imread("person.jpg");
    namedWindow("Face Detection");
    
    string trained_classifier_location = "haarcascade_frontalface_alt.xml";
    CascadeClassifier faceDetector;
    faceDetector.load(trained_classifier_location);
    
    vector<Rect> faces;
    faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(20,20));
    
    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(image_with_humanface, 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 at(x,y)= (" << horizontal << "," << vertical << ")" << endl;
    imshow("Face Detection", image_with_humanface);
    waitKey(0);
    return 0;
}

จุดสำคัญ

  • โหลดภาพนิ่งด้วย imread()
  • ใช้ Ellipse เพื่อให้ได้ Center Point ชัดเจน
  • คำนวณพิกัด: center.x = x + width/2, center.y = y + height/2
  • แสดงพิกัดทาง Console หลังจบลูป

ผลลัพธ์

แสดงภาพพร้อมวงรีล้อมใบหน้า และพิมพ์พิกัดศูนย์กลางใน Console

วิธีติดตามตำแหน่งใบหน้าใน OpenCV ด้วย C++