이미지에 있는 얼굴의 수를 계산하는 것은 쉽습니다. 이전 섹션에서 작성한 프로그램은 이미 '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;
} 출력
