如何使用 C++ 在 OpenCV 中追踪人脸位置?
opencvc++server side programmingprogramming
当我们想要追踪人脸位置时,最好用椭圆形将人脸包围起来,因为椭圆形有一个中心。这个中心也是检测到的人脸的中心点。这样,追踪检测到的人脸位置会更加准确。
以下程序追踪检测到的人脸的中心,并在控制台窗口中显示该位置。 −
示例
#include<iostream> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> //此头文件包含"rectangle()"函数的定义// #include<opencv2/objdetect/objdetect.hpp> //此头文件包含级联分类器的定义// #include<string> using namespace std; using namespace cv; int main(int argc, char** argv){ Mat image_with_humanface;//声明一个矩阵,用于加载包含人脸的图像// image_with_humanface = imread("person.jpg");//加载一张包含人脸的图像// namedWindow("Face Detection");//声明一个窗口,用于显示结果// string training_classifier_location = "C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";//以字符串形式定义 XML 训练分类器的位置// CascadeClassifier faceDetector;//声明一个名为"人脸检测器"的 CascadeClassifier 类的对象// faceDetector.load(trained_classifier_location);//在对象中加载 XML 训练分类器// vector<Rect>faces;//声明一个名为 faces 的矩形向量// faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE,Size(20,20));//检测"image_with_humanfaces"矩阵中的人脸// for (int i = 0; i < faces.size(); i++){ //启动for循环以检测最大的人脸// 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, 8, 0);//在人脸上画一个椭圆// int Horizontal = (faces[i].x + faces[i].width * 0.5);//获取水平坐标值// int Vertical = (faces[i].y + faces[i].width * 0.5);//获取垂直坐标值// } cout << & "人脸的位置在(x,y)=<< & " (<<<CAP_PROP_XI_DECIMATION_HORIZONTAL<<",<<CAP_PROP_XI_DECIMATION_VERTICAL<<")<< endl;// imshow("人脸检测<, image_with_humanface);//显示最大的人脸// waitKey(0);//To wait for keystroke to terminate the program return 0; }