Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีนับจำนวนใบหน้าใน OpenCV ด้วย C++


ภาพรวม

สาธิตการ นับจำนวนใบหน้า (Count Faces) ในภาพนิ่ง โดยใช้ขนาดของ Vector ที่ detectMultiScale() คืนค่า

โค้ดตัวอย่าง C++

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <string>
using namespace std;
using namespace cv;

int main(int argc, char** argv) {
    Mat image_with_humanface = imread("friends.jpg");
    
    string trained_classifier_location = "haarcascade_frontalface_alt.xml";
    CascadeClassifier faceDetector;
    faceDetector.load(trained_classifier_location);
    
    vector<Rect> faces;
    faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(20,20));
    
    int x = faces.size();  // จำนวนใบหน้า
    cout << "Number of face(s) in the image = " << x << endl;
    
    system("pause");
    return 0;
}

คำอธิบาย

  • faces.size() คืนค่าจำนวน Rectangles ที่ตรวจจับได้ = จำนวนใบหน้า
  • เก็บในตัวแปร int x แล้วพิมพ์ออก Console
  • ใช้ system("pause") หยุดหน้าจอ Console เพื่อดูผล

ผลลัพธ์

แสดงจำนวนใบหน้าใน Console (ตัวอย่าง: "Number of face(s) in the image = 3")

วิธีนับจำนวนใบหน้าใน OpenCV ด้วย C++