Real time face detection in C++ using Haar Cascade on OpenCV

I was using mostly Python to experiment AI/ML until recently but now it is time to find ways to improve the performance by making use of all the possible resources such as GPU, and including experimental change of language to C++. Here is the sample code I ported from simple Python face detection (not recognition) Hello-World program, and thought to bookmark for future. This uses Haar Cascade machine learning algorithm and you can read more about it here. Definitely, compared to Python code I feel there is some improvement in the performance, which I will publish the benchmarks later in another blog post.

Note: Error handling and other best practice aspects has not been considered in this sample.

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
VideoCapture cap;
cap.open(0);

CascadeClassifier face_cascade;
face_cascade.load("D:\\OpenCV\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_alt.xml");

while (waitKey(10) != 27) //Press ESC to exit
{
Mat frame;
cap >> frame;

std::vector<Rect> faces;
face_cascade.detectMultiScale(frame, faces, 1.1, 3,0, Size(20, 20));

for(size_t i = 0; i < faces.size(); i++) {
rectangle(frame, faces[i], Scalar(255, 255, 255), 1, 1, 0);
}

imshow("Webcam", frame);
}
}

fd