#include <iostream>
#include <sstream>

#include <opencv2/opencv.hpp>

using namespace std;

void doJob() {
  string path = "";
  string cascadeName = "haarcascade_frontalface_alt.xml";
  cv::CascadeClassifier cascade;
  if (!cascade.load(path + cascadeName)) throw runtime_error(cascadeName + " not found");

  cv::VideoCapture cap(0);
  if (!cap.isOpened()) throw runtime_error("VideoCapture open failed");  
  cv::Mat image;
  cv::Mat gray;
  while (1) {
    cap >> image;
    cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
    equalizeHist(gray, gray);
    vector<cv::Rect> founds;
    cascade.detectMultiScale(gray, founds, 1.1, 2, 0 | cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30));
    for (auto faceRect: founds) {
      cv::rectangle(image, faceRect, cv::Scalar(0, 0, 255), 2);
    }
    cv::imshow("video", image);
    auto key = cv::waitKey(1);
    if (key == 'q') break;
  }
  cv::destroyAllWindows();
}

int main(int argc, char** argv) {
  try {
    doJob();
  }
  catch (exception &ex) {
    cout << ex.what() << endl;
    string s;
    cin >> s;
  }
  return 0;
}
