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

void DrawTransRec(IplImage* img,int x,int y,int width,int height,CvScalar color,double alpha)
{
    IplImage * rec=cvCreateImage(cvSize(width,height),img->depth,img->nChannels);
    cvRectangle(rec,cvPoint(0,0),cvPoint(width,height),color,-1);
    cvSetImageROI(img,cvRect(x,y,width,height));
    cvAddWeighted(img,alpha,rec,1-alpha,0.0,img);
    cvResetImageROI(img);
}

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;

CvCapture * capture;

if((capture = cvCreateCameraCapture(2))==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("pupil");
	cvNamedWindow("dst");
//    cvNamedWindow("eye");
//	cvNamedWindow("gray");
//	cvNamedWindow("binary");
	IplImage *frame0,* segment,*dst,*eye;
	IplImage *frame, *frame1,*gray;
    frame0 = cvQueryFrame(capture);
	
	segment=cvCreateImage(cvGetSize(frame0),8,1);
	dst=cvCreateImage(cvGetSize(frame0),8,3);
//	pupil=cvCreateImage(cvGetSize(img),8,3);
	eye=cvCreateImage(cvGetSize(frame0),8,3);
	frame1=cvCreateImage(cvGetSize(frame0),IPL_DEPTH_8U,1);
    gray = cvCreateImage(cvGetSize(frame0),IPL_DEPTH_8U,1);
	frame=cvCreateImage(cvGetSize(frame0),8,3);
	CvMemStorage* storage=cvCreateMemStorage(6400);
   
	CvSeq* contour=0;

//	CvMemStorage* storage1=cvCreateMemStorage(6400);
//	CvSeq* contour1=0;
	while(1)
	{   
		frame0 = cvQueryFrame(capture);
	    
		cvFlip(frame0,NULL,1);
		cvCvtColor(frame0,gray,CV_BGR2GRAY);
		cvThreshold(gray, frame1,10, 255, CV_THRESH_BINARY); 
        cvCvtColor(frame1,frame,CV_GRAY2BGR);
		if(!frame) break;
		unsigned char *p,*q;
		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;
			}
		}
		
		
	//	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,scenery,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; 
					} 
				}
			double x,y;
			//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;
		//	cvCircle( pupil, cvPoint(x,y), 1000, CV_RGB(0,0,0), 1000, 8, 0 );
			
		//	cvReleaseImage(&frame1);
			if((aaa>120)&&(bbb>120))
			{		
				cvPolyLine(dst, &pt, &npts, 1, 1, CV_RGB(255,0,0), 1); 
			    
          //      cvCircle(frame1, cvPoint(x,y), 10, CV_RGB(0,0,255), 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;
		//		  cvCircle( eye, cvPoint(x,y), 10, CV_RGB(0,0,255), 3, 8, 0 ); 
			//		cvLine(eye,cvPoint(xx[(iii-1)]+50,yy[(iii-1)]+40),cvPoint(xx[iii]+50,yy[iii]+40),CV_RGB(255,0,0),2,8,0) ; 
				  }
				/*   if((iii>10)&&(yy[(iii)]<160)&&(yy[(iii-1)]<160)&&(yy[(iii-2)]<160)&&kk==0)
				  {
				     keybd_event(38, 0, 0, 0); //前进 
					 kk=1;
				   }
                   if((iii>10)&&(yy[(iii)]>160)&&(xx[(iii)]>240)&&(xx[(iii)]<400)&&kk==1)
				  {
				     keybd_event(38, 0, 0, 0); //前进  	
					 kkk=1;
				   }
				   if((iii>10)&&(yy[(iii)]<160)&&(yy[(iii-1)]<160)&&(yy[(iii-2)]<160)&&kkk==1)
				  {
					 kkkk=1;kk=0;
				   }
				    if((iii>10)&&(yy[(iii)]>160)&&(xx[(iii)]>240)&&(xx[(iii)]<400)&&kkkk==1)
				  {
				     kkk=0;kkkk=0;	
					 
				   }
				   
				  if((iii>10)&&(xx[(iii-1)]<200)&&(xx[(iii-3)]<200)&&(xx[(iii-5)]<200)&&(xx[(iii-7)]<200)&&(xx[(iii-9)]<200))
				  {
				  keybd_event(37, 0, 0, 0);  // 向左转
				  }
				  if((iii>10)&&(xx[(iii-1)]>360)&&(xx[(iii-3)]>360)&&(xx[(iii-5)]>360)&&(xx[(iii-7)]>360)&&(xx[(iii-9)]>360))
				  {
				  keybd_event(39, 0, 0, 0);  // 向右转
				  }*/
				  
				  
				  tt=0;
				  iii++;
				}
				
				
			}


		if((aaa>80)&&(bbb>80)&&(((rect_pts[0].x+rect_pts[2].x)/2)<550)&&(((rect_pts[0].y+rect_pts[2].y)/2)<400)
				&&(((rect_pts[0].x+rect_pts[2].x)/2)>50)&&(((rect_pts[0].y+rect_pts[2].y)/2)>50))	
		{	
			if(x>0&&x<240&&y>160&&y<320)
			{
				keybd_event(40,0,0,0);
				
			}
            if(x>200&&x<440&&y>0&&y<160)
			{
				keybd_event(38,0,0,0);
				
			}
		
            if(x>400&&x<640&&y>160&&y<320)
			{
			    keybd_event(39,0,0,0);
				 
			}
		}
		}
/*		if(cvWaitKey(1)=='s')
		{
				
			printf("连通区域最小外接矩形顶点坐标分别为:\n"); 
			printf("(%d,%d)\n",rect_pts[i].x,rect_pts[i].y); 
			printf("最小外接矩形的长为：%d，宽为：%d。\n\n",aaa,bbb); 
		}
*/
    


		cvShowImage("dst",dst);
	//	cvShowImage("binary",frame);
		cvShowImage("src",frame0);
	//	cvShowImage("pupil",pupil);
    //    cvShowImage("eye",eye);
	//	cvShowImage("gray",gray);
	//	if (iii==200) break;
		char c=cvWaitKey(10);
		if(c==27)
			break;
	}
	cvReleaseCapture(&capture);//可不调用此函数，CCameraDS析构时会自动关闭摄像头
    
	cvDestroyWindow("camera");
	
	return 0;
}

//cvReleaseCapture(&capture);
//cvDestroyWindow("Camera Show");
