#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;
int main(int argc,char**argv)
{

  Mat img=imread("crowd.png");
  if (!img.data) return EXIT_FAILURE;

  HOGDescriptor hog;
  vector<Rect> found, filtered;

  hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector()); 
  hog.detectMultiScale(img,found,0,Size(8,8),Size(32,32),1.05,2);

  for(int i=0,j;i<found.size();i++)
  {
     for(j=0;j<found.size();j++)
       if (j!=i && (found[i] & found[j])==found[i]) break;
     if (j==found.size())
       filtered.push_back(found[i]);
  }

  CvMat img_tmp=img;

  for(int i=0;i<filtered.size();i++)
  {
    Rect rect=filtered[i];
    rectangle(img,rect.tl(),rect.br(),CV_RGB(0,255,0),3);
  }

  CvHaarClassifierCascade *cascade=(CvHaarClassifierCascade*)cvLoad("fullbody.xml");
  if (!cascade) return EXIT_FAILURE;
  CvMemStorage *storage=cvCreateMemStorage();
  CvSeq *people=cvHaarDetectObjects(&img_tmp,cascade,storage,1.1,2,0,Size(30,30));
  
  for(int i=0;i<people->total;i++)
  {
    Rect *rect=(Rect*)cvGetSeqElem(people,i);
    rectangle(img,rect->tl(),rect->br(),CV_RGB(255,0,0),3);
  }
   
  //imshow("people",img);
  imwrite("people.png",img);
  //waitKey();
  cvReleaseData(&img_tmp);
  cvReleaseMemStorage(&storage);
  cvReleaseHaarClassifierCascade(&cascade);
  return EXIT_SUCCESS;
}
