raw snippet

An example to use OpenCV2 for Face detection with JSON export in C++

// Copyright Robert Eisele 2014
#include <iostream>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>

using namespace cv;
using namespace std;

int main(int argc, char *argv[]) {

  CascadeClassifier cascade;
  if (argc != 3) {
    cerr << "Pass two arguments: <image> <haar-file>" << endl;
    return 1;
  }

  Mat img;
  Mat gray;
  std::vector<Rect> faces;

  img = imread(argv[1]);

  if (!img.data) {
    cerr << "Image could not be loaded." << endl;
    return 1;
  }

  if (!cascade.load(argv[2])) {
    cerr << "Haar-cascade file could not be loaded" << endl;
    return 1;
  }

  cvtColor(img, gray, COLOR_BGR2GRAY);
  equalizeHist(gray, gray);

  cascade.detectMultiScale(gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));

  cout << "[";

  for (size_t i = 0; i < faces.size(); i++) {

    if (i > 0) cout << ",";

    cout << "{";
    cout << "\"x\":" << faces[i].x << ",";
    cout << "\"y\":" << faces[i].y << ",";
    cout << "\"w\":" << faces[i].width << ",";
    cout << "\"h\":" << faces[i].height << "}";
  }
  cout << "]";

  return 0;
}