如何使用C++在 OpenCV 实时跟踪人脸?
我们将学习如何使用 OpenCV 实时跟踪人脸。此程序与之前的程序相同,不同之处在于我们使用椭圆形而不是矩形来识别面部,我们还使用额外的“cout”语句在控制台窗口中显示面部的坐标。
以下是实时检测人脸的程序 -
示例
#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;
}输出


广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP