#include "stdafx.h"
#include <cxcore.h>
#include"cv.h"
#include"highgui.h"
#include"windows.h"
#include <conio.h>
#include "ShellAPI.h"

int main()
{
int xx[10000];
int yy[10000];
int iii=0;
int ii=0;
long int tt=0;
int kk=0;
int kkk=0;
int kkkk=0;
int qqq[48]={0};
double x21=0,y21=0;
double x22=0,y22=0;
double x=0,y=0;
double x1=0,y1=0;
unsigned char yyyyy[10000]={0};
int t6=0;
CvCapture * capture;
CvCapture * capture1;
FILE *fp2 = fopen("d:\\b.txt","w");;//定义文件流指针，用于打开写操作的文件
if((capture = cvCreateCameraCapture(2))==NULL)
{
printf("Camera Open Fail!Please check your Camera.");
//char c=cvWaitKey(33);
return 0;
}
if((capture1 = cvCreateCameraCapture(1))==NULL)
{
printf("Camera Open Fail!Please check your Camera.");
//char c=cvWaitKey(33);
return 0;
}

/*cvNamedWindow("Camera Show",CV_WINDOW_AUTOSIZE);
IplImage * frame;
cvWaitKey(300);
while(1)
{
frame=cvQueryFrame(capture);
if(!frame)
break;
cvShowImage("Camera Show",frame);
char c=cvWaitKey(33);
if(c==27)
break;


}*/
    cvNamedWindow("src");
	cvNamedWindow("6");
//	cvNamedWindow("pupil");
	cvNamedWindow("dst");
//    cvNamedWindow("eye");
	cvNamedWindow("scenery");
	cvMoveWindow("src",0,0);
	cvMoveWindow("dst",600,0);
	cvMoveWindow("scenery",350,200);
	IplImage* frame0,*frame5,* segment,*segment1,*dst,*eye,*scenery,*gray,*frame2,*frame,*frame6;
	
    frame0 = cvQueryFrame(capture);
/*	frame5 = cvQueryFrame(capture1);
	CvSize size = cvSize(frame5->width * 2,frame5->height*2); 
    IplImage* frame1 = cvCreateImage(size,frame5->depth,frame5->nChannels);
	cvPyrUp( frame5, frame1, CV_GAUSSIAN_5x5 );*/
	//IplImage* frame0; 
	//cvCopy(frame3,frame0,NULL);
	//frame0 = DoPyrDown(frame0);
	segment=cvCreateImage(cvGetSize(frame0),8,1);
	segment1 = cvCreateImage(cvGetSize(frame0),8,1);
	dst=cvCreateImage(cvGetSize(frame0),8,3);
//	pupil=cvCreateImage(cvGetSize(img),8,3);
	eye=cvCreateImage(cvGetSize(frame0),8,3);
	scenery=cvCreateImage(cvGetSize(frame0),8,3);
	frame2=cvCreateImage(cvGetSize(frame0),IPL_DEPTH_8U,1);
    gray = cvCreateImage(cvGetSize(frame0),IPL_DEPTH_8U,1);
	frame=cvCreateImage(cvGetSize(frame0),8,3);
    frame6 = cvCreateImage(cvGetSize(frame0),8,3);

	CvMemStorage* storage=cvCreateMemStorage(6400);
   
	CvSeq* contour=0;
    

	CvMemStorage* storage1=cvCreateMemStorage(6400);
	CvSeq* contour1=0;
	while(1)
	{   
		frame0 = cvQueryFrame(capture);
		cvCvtColor(frame0,gray,CV_BGR2GRAY);
		cvThreshold(gray, frame2,10, 255, CV_THRESH_BINARY); 
        cvCvtColor(frame2,frame,CV_GRAY2BGR);
	//	frame1 = cvQueryFrame(capture1);
		frame5 = cvQueryFrame(capture1);
	CvSize size = cvSize(frame5->width * 2,frame5->height*2); 
    IplImage* frame1 = cvCreateImage(size,frame5->depth,frame5->nChannels);
	cvPyrUp( frame5, frame1, CV_GAUSSIAN_5x5 );
		cvFlip(frame,NULL,1);
		cvFlip(frame0,NULL,1);
		if(!frame) break;
		unsigned char *p,*q;
		unsigned char *p1,*q1;
		for(int i=0;i<frame->height;i++)
		{
			p=(unsigned char*)(frame->imageData+i*frame->widthStep);
			q=(unsigned char*)(segment->imageData+i*segment->widthStep);
			for(int j=0;j<frame->width;j++)
			{
				double r,g,b;
				r=(double)(*(p+j*3+2))/255.0;
				b=(double)(*(p+j*3))/255.0;
				g=(double)(*(p+j*3+1))/255.0;
				unsigned char f = 255*((r<0.12)&&(g<0.12)&&(b<0.12));
                *(q+j)=f;
			}
		}
		
		for(int i1=0;i1<frame1->height;i1++)
		{
			p1=(unsigned char*)(frame1->imageData+i1*frame1->widthStep);
			q1=(unsigned char*)(segment1->imageData+i1*segment1->widthStep);
			for(int j1=0;j1<frame1->width;j1++)
			{
				double r1,g1,b1;
				r1=(double)(*(p1+j1*3+2))/255.0;
				b1=(double)(*(p1+j1*3))/255.0;
				g1=(double)(*(p1+j1*3+1))/255.0;
				unsigned char f1 = 255*((r1>0.4)&&(g1<0.4)&&(b1<0.4));
                *(q1+j1)=f1;
			}
		}
		
	//	cvSmooth(segment,segment,CV_GAUSSIAN);
	//	cvDilate(segment,segment,NULL,2);
	//	cvErode(segment,segment,NULL,2);
	//	cvSmooth(segment,segment,CV_GAUSSIAN);
		cvCvtColor(segment,dst,CV_GRAY2RGB);

		cvSmooth(segment1,segment1,CV_GAUSSIAN);
		cvDilate(segment1,segment1,NULL,2);
		cvErode(segment1,segment1,NULL,2);
		cvSmooth(segment1,segment1,CV_GAUSSIAN);
		cvCvtColor(segment1,frame6,CV_GRAY2RGB);
	//	cvCvtColor(segment,pupil,CV_GRAY2RGB);
		
		IplImage* segment2=cvCloneImage(segment);
		cvFindContours(segment2,storage,&contour,sizeof(CvContour),CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);

		IplImage* segment3=cvCloneImage(segment1);
		cvFindContours(segment3,storage1,&contour1,sizeof(CvContour),CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);
	
    	
		for(;contour!=0;contour=contour->h_next) 
		{   
            
			CvBox2D rect=cvMinAreaRect2(contour,storage); 
			CvPoint2D32f rect_pts0[4]; 
			cvBoxPoints(rect, rect_pts0);
			
            int aaa=0,bbb=0,npts=4,k=0;;

			CvPoint rect_pts[4], *pt = rect_pts; 

			for (int i=0; i<4; i++) 
				{ 
					rect_pts[i]= cvPointFrom32f(rect_pts0[i]); 
				
					aaa=(int) sqrt((double)(rect_pts[0].x-rect_pts[1].x)*(rect_pts[0].x-rect_pts[1].x)+(double)(rect_pts[0].y-rect_pts[1].y)*(rect_pts[0].y-rect_pts[1].y)); 
					bbb=(int) sqrt((double)(rect_pts[0].x-rect_pts[3].x)*(rect_pts[0].x-rect_pts[3].x)+(double)(rect_pts[0].y-rect_pts[3].y)*(rect_pts[0].y-rect_pts[3].y)); 
					if(aaa<bbb) 
					{ 
					k=aaa; 
					aaa=bbb; 
					bbb=k; 
					} 
				}
			
			//int a,b;
         	x=(rect_pts[0].x+rect_pts[2].x)/2.0;
			y=(rect_pts[0].y+rect_pts[2].y)/2.0;

  //      if (kbhit()) break;
		
			if((aaa>120)&&(bbb>120))
			{		
			//	cvPolyLine(dst, &pt, &npts, 1, 1, CV_RGB(255,0,0), 1); 
			    x1 = 320+(x-320)*320/240;
				y1 = 240+(y-240)*240/180;
                cvCircle(frame1, cvPoint(x1,y1), 10, CV_RGB(255,255,0), 3, 8, 0 ); 
          //      cvCircle(dst, cvPoint(x,y), 10, CV_RGB(0,0,255), 3, 8, 0 );
                xx[iii]=x;
				yy[iii]=y;
				
                
			    CvFont font;
			    cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX,0.5,0.5);
			    char text[50];
			    sprintf(text,"(%.1f,%.1f)",x,y);
			    cvPutText(dst,text,rect_pts[1],&font,CV_RGB(0,255,0));
				tt++;
				if(tt==2)
				{
				  if(iii==9999) iii=0;
				///  printf("iii=%d \n",iii);
				///  printf("x=%d, ",xx[iii]);
               ///   printf("y=%d",yy[iii]);
				///  printf("\n");
				  if(iii>0)
				  {
		             if(iii==9999) iii=0;
				  }
				  tt=0;
				  iii++;
				}
				
				
			}

		}
		for(;contour1!=0;contour1=contour1->h_next) 
		{   
            
			CvBox2D rect1=cvMinAreaRect2(contour1,storage1); 
			CvPoint2D32f rect1_pts0[4]; 
			cvBoxPoints(rect1, rect1_pts0);
			
            int aaa1=0,bbb1=0,npts1=4,k1=0;;

			CvPoint rect1_pts[4], *pt1 = rect1_pts; 

			for (int i=0; i<4; i++) 
				{ 
					rect1_pts[i]= cvPointFrom32f(rect1_pts0[i]); 
				
					aaa1=(int) sqrt((double)(rect1_pts[0].x-rect1_pts[1].x)*(rect1_pts[0].x-rect1_pts[1].x)+(double)(rect1_pts[0].y-rect1_pts[1].y)*(rect1_pts[0].y-rect1_pts[1].y)); 
					bbb1=(int) sqrt((double)(rect1_pts[0].x-rect1_pts[3].x)*(rect1_pts[0].x-rect1_pts[3].x)+(double)(rect1_pts[0].y-rect1_pts[3].y)*(rect1_pts[0].y-rect1_pts[3].y)); 
					if(aaa1<bbb1) 
					{ 
					k1=aaa1; 
					aaa1=bbb1; 
					bbb1=k1; 
					} 
				}
			
			//int a,b;
         	x21=(rect1_pts[0].x+rect1_pts[2].x)/2.0;
			y21=(rect1_pts[0].y+rect1_pts[2].y)/2.0;

  //      if (kbhit()) break;
		
			if((aaa1>40)&&(bbb1>40))
			{		
				cvPolyLine(frame6, &pt1, &npts1, 1, 1, CV_RGB(255,0,0), 1); 
			  
		//		if(x1<rect1_pts[0].x||x1>rect1_pts[2].x||y1<rect1_pts[0].y||y1>rect1_pts[2].y)
	     //     {
        
		       yyyyy[t6] = (char)sqrt((double)(x1-x21)*(x1-x21)+(double)(y1-y21)*(y1-y21));
		       t6++;
       
	       //    }
	       //     else
	       //    {yyyyy[t6]=0;t6++;}
	           if(t6==9999) {
		            for (int i=1;i<t6-1;++i)
                   {
	                 fprintf(fp2,"%d       ",i);
                     fprintf(fp2,"%d\n",yyyyy[i]);  
                    }
                   fclose(fp2);	
		            while(1);
	             }
                
			    CvFont font1;
			    cvInitFont(&font1,CV_FONT_HERSHEY_SIMPLEX,0.5,0.5);
			    char text1[50];
			    sprintf(text1,"(%.1f,%.1f)",x21,y21);
			    cvPutText(frame6,text1,rect1_pts[1],&font1,CV_RGB(0,255,0));
				
			}
  
	  
        
		}
	
        
		cvShowImage("dst",dst);
		cvShowImage("src",frame0);
	//	cvShowImage("pupil",pupil);
    //    cvShowImage("eye",eye);
		cvShowImage("scenery",frame1);
		cvShowImage("6",frame6);
	//	cvReleaseImage(&frame5);
		   if(GetKeyState(VK_F7)<0) 
	    { 
	       for (int i=1;i<t6;++i)
         {
		 fprintf(fp2,"%d       ",i);
        fprintf(fp2,"%d\n",yyyyy[i]);
       
       }
          fclose(fp2);
	     
	ShellExecute(NULL,   "open", "C:\\Users\\liuhua\\Desktop\\result.m",   NULL,   NULL, SW_SHOWNORMAL);
   keybd_event(115, 0, 0, 0);
			
			while(1);
	     
	      
	   }
	
 
 
		cvReleaseImage(&frame1);
		char c=cvWaitKey(10);
		if(c==27)
			break;
	}
	//if(kbhit()) 
//	while(1);
	
	cvReleaseCapture(&capture);//可不调用此函数，CCameraDS析构时会自动关闭摄像头
    cvReleaseCapture(&capture1);//可不调用此函数，CCameraDS析构时会自动关闭摄像头
	cvDestroyWindow("camera");
	cvReleaseImage(&frame5);
	cvReleaseImage(&frame6);
//	cvReleaseVideoWriter(&writer);
	
	
	return 0;
}
