如何使用 C++ 來計算 OpenCV 中識別的面部數量?


計算影像中的面部數量很容易。我們在上一節中編寫的程式已經具有“faces.size()”中的人臉數量的資訊。此程式碼-“faces.size()”賦予了一個整數值。

例如,如果我們寫“int x = faces.size()”,則“x”將包含人臉的數量。

以下程式從給定的影像中計算出人臉數量並將其顯示在控制檯視窗中。

示例

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#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 image_with_humanface;//Declaring a matrix to load image with human faces//
   image_with_humanface = imread("friends.jpg");//loading an image that contains human face in it//
   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//
   faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(20, 20));//Detecting the faces in 'image_with_humanfaces' matrix//
   int x = faces.size();//Calculating the number of faces and storing the integer value in x//
   cout << "Number of face(s)in the image=" << x << endl;//Displaying the value of x in the console window//
   system("pause");//Pausing the system to visualize the result//
   return 0;
}

輸出

更新於: 2021 年 3 月 10 日

283 次瀏覽

開啟你的 職業

透過完成課程來獲得認證

入門
廣告
© . All rights reserved.