#include "opencv2/opencv.hpp"

#define FILENAME "face2.png"
#define WNAME "faces"

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

  IplImage *img=cvLoadImage(FILENAME);
  if (!img) return EXIT_FAILURE;

  CvSize imsize=cvGetSize(img);
	IplImage* back_img=cvCreateImage(imsize ,IPL_DEPTH_8U,1);
	IplImage* hsv=cvCreateImage(imsize,IPL_DEPTH_8U,3);
	cvCvtColor(img,hsv,CV_BGR2HSV);

	IplImage* h_plane=cvCreateImage(cvGetSize(img),IPL_DEPTH_8U,1);
	IplImage* s_plane=cvCreateImage(cvGetSize(img),IPL_DEPTH_8U,1);
  IplImage* v_plane=cvCreateImage(cvGetSize(img),IPL_DEPTH_8U,1);
	IplImage* planes[]={h_plane,s_plane};
  cvSplit(hsv,h_plane,s_plane,v_plane,NULL);

	int h_bins=30,s_bins=32;
  int hist_size[]={h_bins,s_bins};
	float h_ranges[]={0,180};
	float s_ranges[]={0,255};
	float* ranges[]={h_ranges,s_ranges};
	CvHistogram* hist=cvCreateHist(2,hist_size,CV_HIST_ARRAY,ranges,1);
	cvCalcHist(planes,hist,0,0);
	cvNormalizeHist(hist,40*255);

	cvCalcBackProject(planes,back_img,hist);
	cvNormalizeHist(hist,1.0);

  //cvThreshold(back_img,back_img,65,255,CV_THRESH_BINARY);
  cvAdaptiveThreshold(back_img,back_img,255,CV_ADAPTIVE_THRESH_MEAN_C,CV_THRESH_BINARY,21);

  IplImage *mask=cvCreateImage(imsize,IPL_DEPTH_8U,1);

  /*
  cvZero(mask);
  uchar * ptr1,*ptr2,*ptr3;

  for(int i=0;i<img->height;i++)
    for(int j=0;j<img->width;j++)
    {
      ptr1=cvPtr2D(v_plane,i,j);
      ptr2=cvPtr2D(back_img,i,j);
      ptr3=cvPtr2D(mask,i,j);

      if (*ptr2==255)
        if (*ptr1==*ptr2)
          *ptr3=0;
        else
          *ptr3=255;
    }

  cvSmooth(mask,mask);

  cvErode(mask,mask,NULL,3);
  cvDilate(mask,mask,NULL,5);
  
  //cvNot(mask,mask);
*/
  cvShowImage("asdf",back_img);
  cvWaitKey();
  //cvSaveImage("out.png",mask);

  cvReleaseImage(&hsv);
  cvReleaseImage(&h_plane);cvReleaseImage(&s_plane);
  cvReleaseImage(&v_plane);cvReleaseImage(&img);
  cvReleaseImage(&mask);cvReleaseImage(&back_img);
  return EXIT_SUCCESS;
}
