Computer >> Máy Tính >  >> Lập trình >> C ++

Làm cách nào để theo dõi khuôn mặt trong thời gian thực trong OpenCV bằng C ++?

Chúng ta sẽ tìm hiểu cách theo dõi khuôn mặt trong thời gian thực trong OpenCV. Chương trình này giống với chương trình trước và điểm khác biệt là chúng tôi sử dụng hình elip thay vì hình chữ nhật để xác định khuôn mặt và chúng tôi cũng sử dụng câu lệnh 'cout' bổ sung để hiển thị tọa độ của khuôn mặt trong cửa sổ giao diện điều khiển.

Chương trình sau để phát hiện khuôn mặt người trong thời gian thực -

Ví dụ

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
//This header includes definition of 'rectangle()' function//
#include<opencv2/objdetect/objdetect.hpp>
//This header includes the definition of Cascade Classifier//
#include<string>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
   Mat video_stream;//Declaring a matrix hold frames from video stream//
   VideoCapture real_time(0);//capturing video from default webcam
   namedWindow("Face Detection");//Declaring an window to show the result//
   string trained_classifier_location = "C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";//Defining the location our XML Trained Classifier in a string//
   CascadeClassifier faceDetector;//Declaring an object named 'face detector' of CascadeClassifier class//
   faceDetector.load(trained_classifier_location);//loading the XML trained classifier in the object//
   vector<Rect>faces;//Declaring a rectangular vector named faces//
   while (true) {
      faceDetector.detectMultiScale(video_stream, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(30, 30));//Detecting the faces in 'image_with_humanfaces' matrix//
      real_time.read(video_stream);// reading frames from camera and loading them in 'video_stream' Matrix//
      for (int i = 0; i < faces.size(); i++){ //for locating the face
         Point center(faces[i].x + faces[i].width * 0.5, faces[i].y + faces[i].height * 0.5);//getting the center of the face//
         ellipse(video_stream, center,Size(faces[i].width * 0.5, faces[i].height * 0.5), 0, 0, 360, Scalar(255, 0, 255), 4, 8, 0);//draw an ellipse on the face//
         int horizontal = (faces[i].x + faces[i].width * 0.5);//Getting the horizontal value of coordinate//
         int vertical=(faces[i].y + faces[i].width * 0.5);//Getting the vertical value of coordinate//
         cout << "Position of the face is:" << "(" << horizontal << "," << vertical << ")" << endl;
         //Showing position in the console window//
      }
      imshow("Face Detection", video_stream);
      //Showing the detected face//
      if (waitKey(10) == 27){ //wait time for each frame is 10 milliseconds//
         break;
      }
   }
   return 0;
}

Đầu ra

Làm cách nào để theo dõi khuôn mặt trong thời gian thực trong OpenCV bằng C ++?

Làm cách nào để theo dõi khuôn mặt trong thời gian thực trong OpenCV bằng C ++?