示例#1
0
int main() {
    CvCapture* capture =0;
    capture = cvCaptureFromCAM(0);
    if(!capture) {
       printf("Capture failure\n");
       return -1;
    }
    
    IplImage* frame=0;
    frame = cvQueryFrame(capture);
    if(!frame) return -1;
   
   //create a blank image and assigned to 'imgTracking' which has the same size of original video
   imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);
   cvZero(imgTracking); //covert the image, 'imgTracking' to black

   cvNamedWindow("Video");
   cvNamedWindow("Ball");

      //iterate through each frames of the video
   while(true) {
      frame = cvQueryFrame(capture);
      if(!frame) break;
      frame=cvCloneImage(frame);

      cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

      IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3);
      cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV
      IplImage* imgThresh = GetThresholdedImage(imgHSV);
        
      cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel
          
      //track the possition of the ball
      trackObject(imgThresh);

      // Add the tracking image and the frame
      cvAdd(frame, imgTracking, frame);

      cvShowImage("Ball", imgThresh);
      cvShowImage("Video", frame);
         
         //Clean up used images
      cvReleaseImage(&imgHSV);
      cvReleaseImage(&imgThresh);
      cvReleaseImage(&frame);

      //Wait 10mS
      int c = cvWaitKey(10);
      //If 'ESC' is pressed, break the loop
      if((char)c==27 ) break;
    }

    cvDestroyAllWindows();
    cvReleaseImage(&imgTracking);
    cvReleaseCapture(&capture);

    return 0;
}
示例#2
0
int main(){
 CvCapture* capture =0; 
 
 capture = cvCaptureFromCAM(0);

 if(!capture){
   printf("Capture failure\n");
   return -1;
 }

 cvSetCaptureProperty(capture,CV_CAP_PROP_FRAME_WIDTH,320);
 cvSetCaptureProperty(capture,CV_CAP_PROP_FRAME_HEIGHT,240);
 cvSetCaptureProperty(capture,CV_CAP_PROP_FPS,50);

 IplImage* frame=0;
  
 setwindowSettings();

  //iterate through each frames of the video
 while(true){
 
  frame = cvQueryFrame(capture);
  if(!frame)  break;
  frame=cvCloneImage(frame); 

  // optional load an image
  //frame = cvLoadImage("imagen3.png",CV_LOAD_IMAGE_COLOR );

  cvSmooth(frame, frame, CV_GAUSSIAN,3,3);

  IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
  cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV
   
  IplImage* imgThresh = GetThresholdedImage(imgHSV);
  
  cvShowImage("Ball", imgThresh);
  cvShowImage("Video", frame);

   //Clean up used images
  cvReleaseImage(&imgHSV);
  cvReleaseImage(&imgThresh);
  cvReleaseImage(&frame);

   //Wait 80mS
  int c = cvWaitKey(80);
  //If 'ESC' is pressed, break the loop
  if((char)c==27 ) break;

 }

  cvDestroyAllWindows();
 cvReleaseCapture(&capture);

       return 0;
}
示例#3
0
文件: Camera.c 项目: mclarkk/tsat
int white_pixel_count() {
     int white_pix_count = 0;
     IplImage* frame = cvQueryFrame( capture );
     if ( !frame ) {
       fprintf( stderr, "ERROR: frame is null...\n" );
       return -1;
     }
     IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3);
     cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV
     IplImage* imgThresh = GetThresholdedImage(imgHSV);
     CvScalar sum = cvSum(imgThresh);
     white_pix_count = sum.val[0]/255;
          //printf("%f\n", avg.val[0]);
     return white_pix_count;
}
示例#4
0
int main() {
    CvCapture* capture =0;
    capture = cvCaptureFromCAM(0);
    if(!capture) {
        printf("Capture failure\n");
        return -1;
    }

    IplImage* frame=0;

    cvNamedWindow("Video");
    cvNamedWindow("Ball");


    //iterate through each frames of the video
    while(true) {

        frame = cvQueryFrame(capture);
        if(!frame) break;

        frame=cvCloneImage(frame);
        cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

        IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3);
        cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV
        IplImage* imgThresh = GetThresholdedImage(imgHSV);

        cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel

        cvShowImage("Ball", imgThresh);
        cvShowImage("Video", frame);

        //Clean up used images
        cvReleaseImage(&imgHSV);
        cvReleaseImage(&imgThresh);
        cvReleaseImage(&frame);

        //Wait 50mS
        int c = cvWaitKey(10);
        //If 'ESC' is pressed, break the loop
        if((char)c==27 ) break;
    }

    cvDestroyAllWindows() ;
    cvReleaseCapture(&capture);

    return 0;
}
示例#5
0
/**
 * @brief		The program entry point.
 */
int main() {
	CvCapture* capture = 0;

	capture = cvCaptureFromCAM(1);
	if (!capture) {
		printf("Capture failure\n");
		return -1;
	}

	IplImage* frame = 0;

	setwindowSettings();

	//iterate through each frames of the video
	while (true) {

		frame = cvQueryFrame(capture);
		if (!frame)
			break;
		frame = cvCloneImage(frame);

		IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3);
		cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV

		IplImage* imgThresh = GetThresholdedImage(imgHSV);

		cvShowImage("Ball", imgThresh);
		cvShowImage("Video", frame);

		//Clean up used images
		cvReleaseImage(&imgHSV);
		cvReleaseImage(&imgThresh);
		cvReleaseImage(&frame);

		//Wait 80mS
		int c = cvWaitKey(80);
		//If 'ESC' is pressed, break the loop
		if ((char) c == 27)
			break;

	}

	cvDestroyAllWindows();
	cvReleaseCapture(&capture);

	return 0;
}
int main(){
      CvCapture* ambil =0;       

      ambil = cvCaptureFromCAM(0);
      if(!ambil){
            printf("Capture failure\n");
            return -1;
      }
      
      IplImage* frame=0;
      cvNamedWindow("Video");      
      cvNamedWindow("Deteksi Warna");

      //iterasi     
      while(true){

            frame = cvQueryFrame(ambil);            
            if(!frame) break;

            frame=cvCloneImage(frame); 
            cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //menghasilkan penghalusan gambar dengan metode Gaussian kernel

            IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
            cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Merubah format warna from RGB to HSV
            IplImage* imgThresh = GetThresholdedImage(imgHSV);
          
            cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3);
            
            cvShowImage("Deteksi Warna", imgThresh);            
            cvShowImage("Video", frame);
            
          
            cvReleaseImage(&imgHSV);
            cvReleaseImage(&imgThresh);            
            cvReleaseImage(&frame);

            
            int c = cvWaitKey(10);
            //If 'ESC' is pressed, break the loop
            if((char)c==27 ) break;      
      }

      cvDestroyAllWindows() ;
      cvReleaseCapture(&ambil);     

      return 0;
}
示例#7
0
文件: tracker.cpp 项目: jadonk/stache
int main(){
      CvCapture* capture =0;
      CvSize dim;

      FILE *fp;
      fp = fopen("debug.txt","r");
      if(fp) {
          fscanf(fp, "%d", &debug);
          fclose(fp);
      }

      capture = cvCaptureFromCAM(0);
      cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 160);
      cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 120);
      if(!capture){
         printf("Capture failure\n");
         return -1;
      }
      
      IplImage* frame=0;
      frame = cvQueryFrame(capture);           
      if(!frame) return -1;
   
      //create a blank image and assigned to 'imgTracking' which has the same size of original video
      dim = cvGetSize(frame);
      imgTracking=cvCreateImage(dim,IPL_DEPTH_8U, 3);
      cvZero(imgTracking); //covert the image, 'imgTracking' to black

      halfWidth = dim.width/2;
      halfHeight = dim.height/2;

      if(debug>0) {
         cvNamedWindow("Video");     
         cvNamedWindow("Ball");
      }

      //iterate through each frames of the video     
      while(true){

            frame = cvQueryFrame(capture);           
            if(!frame) break;
            frame=cvCloneImage(frame); 
            
            cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

            IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
            cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV
            IplImage* imgThresh = GetThresholdedImage(imgHSV);
          
            cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel
            
            //track the possition of the ball
            trackObject(imgThresh);

            if(debug>1) {
               // Add the tracking image and the frame
               cvAdd(frame, imgTracking, frame);
            }

            if(debug>0) {
               cvShowImage("Ball", imgThresh);           
               cvShowImage("Video", frame);
            }
           
            //Clean up used images
            cvReleaseImage(&imgHSV);
            cvReleaseImage(&imgThresh);            
            cvReleaseImage(&frame);

            //Wait X mS
            int c = cvWaitKey(delay);
            //If 'ESC' is pressed, break the loop
            if((char)c==27 ) break;      
      }

      cvDestroyAllWindows() ;
      cvReleaseImage(&imgTracking);
      cvReleaseCapture(&capture);     

      return 0;
}
示例#8
0
int colour_tracker()
{
	// Initialize capturing live feed from the camera
	CvCapture* capture = 0;
	capture = cvCaptureFromCAM(0);

	// Couldn't get a device? Throw an error and quit
	if(!capture)
    {
        printf("Could not initialize capturing...\n");
        return -1;
    }

	// The two windows we'll be using
    cvNamedWindow("video");
	cvNamedWindow("thresh");

	// This image holds the "scribble" data...
	// the tracked positions of the ball
	IplImage* imgScribble = NULL;

	// An infinite loop
	while(true)
    {
		// Will hold a frame captured from the camera
		IplImage* frame = 0;
		frame = cvQueryFrame(capture);

		// If we couldn't grab a frame... quit
        if(!frame)
            break;

		// If this is the first frame, we need to initialize it
		if(imgScribble == NULL)
		{
			imgScribble = cvCreateImage(cvGetSize(frame), 8, 3);
		}

		// Holds the yellow thresholded image (yellow = white, rest = black)
		IplImage* imgYellowThresh = GetThresholdedImage(frame);

		// Calculate the moments to estimate the position of the ball
		CvMoments *moments = (CvMoments*)malloc(sizeof(CvMoments));
		cvMoments(imgYellowThresh, moments, 1);

		// The actual moment values
		double moment10 = cvGetSpatialMoment(moments, 1, 0);
		double moment01 = cvGetSpatialMoment(moments, 0, 1);
		double area = cvGetCentralMoment(moments, 0, 0);

		// Holding the last and current ball positions
		static int posX = 0;
		static int posY = 0;

		int lastX = posX;
		int lastY = posY;

		posX = moment10/area;
		posY = moment01/area;

		// Print it out for debugging purposes
		printf("position (%d,%d)\n", posX, posY);

		// We want to draw a line only if its a valid position
		if(lastX>0 && lastY>0 && posX>0 && posY>0)
		{
			// Draw a yellow line from the previous point to the current point
			cvLine(imgScribble, cvPoint(posX, posY), cvPoint(lastX, lastY), cvScalar(0,255,255), 5);
		}

		// Add the scribbling image and the frame... and we get a combination of the two
		cvAdd(frame, imgScribble, frame);
		cvShowImage("thresh", imgYellowThresh);
		cvShowImage("video", frame);

		// Wait for a keypress
		int c = cvWaitKey(10);
		if(c!=-1)
		{
			// If pressed, break out of the loop
            break;
		}

		// Release the thresholded image... we need no memory leaks.. please
		cvReleaseImage(&imgYellowThresh);

		delete moments;
    }

	// We're done using the camera. Other applications can now use it
	cvReleaseCapture(&capture);
    return 0;
}
示例#9
0
unsigned __stdcall FrameCaptureThread( void* Param )
{
    cout << "First thread started!" << endl;
    //----------------------------------------------------------
    OpData* pInfo = (OpData*) Param;
    CvSeq** contour = pInfo->ppCont;		//variable for storing contours
    CvCapture* capture = 0;		//interface for capturing frames of the video/camera
    //----------------------------------------------------------
    string strVid = "test";
    strVid.append( NumberToString( pInfo->nConv ) );
    strVid.append( ".avi" );
    //----------------------------------------------------------
    capture = cvCaptureFromAVI( strVid.c_str() );		//select video based on conveyor id
    //capture = cvCaptureFromAVI( "test.avi" );		//should be selection of file/camera here
    if( !capture )
    {
        cout << "Could not initialize capturing..." << endl;
        return 0;
    }
    cvNamedWindow( strVid.c_str() );
    while( true )
    {
        //----------------------------------------------------------
        IplImage* frame = 0;
        //----------------------------------------------------------
        frame = cvQueryFrame( capture );
        if( !frame )
        {
            break;
        }
        //reprocess frame, creating only black & white image
        IplImage* imgThr = GetThresholdedImage( frame );
        //transform image into its binary representation
        cvThreshold( imgThr, imgThr, 128, 255, CV_THRESH_BINARY);
        CvMemStorage* storage = cvCreateMemStorage(0);
        IplImage *imgNew = cvCloneImage( imgThr );
        //find all contours
        cvFindContours( imgNew, storage, contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
        SetEvent( hEvent );
        CvSeq* temp = *contour;

        for( ; temp != 0; temp = temp->h_next )
        {
            cvDrawContours( frame, temp, cvScalar( 104, 178, 70 ), cvScalar( 130, 240, 124 ), 1, 1, 8 );
        }
        //SetEvent( hEvent );
        cvShowImage( strVid.c_str(), frame );
        // Wait for a keypress
        int c = cvWaitKey( 300 );
        if( c != -1 )
        {
            // If pressed, break out of the loop
            break;
        }
        // Release the thresholded image... we need no memory leaks.. please
        cvClearMemStorage( storage );
        cvReleaseMemStorage( &storage );
        cvReleaseImage( &imgNew );
        cvReleaseImage( &imgThr );
    }
    return 0;
}
int main(){
   
      CvCapture* capture =0;       
      capture = cvCaptureFromCAM(0);
      if(!capture){
         printf("Capture failure\n");
         return -1;
      }
      IplImage* frame=0;
	  
      frame = cvQueryFrame(capture);           
      if(!frame) return -1;
   
	  //membuat gambar yang kosong dan menjalankan imgTracking yang memiliki ukuran CvWindow yang sama dari yang asli
     imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);
     cvZero(imgTracking); //menyembunyikan warna yang tidak terdeteksi menjadi hitam
	 //cvCreateTrackbar("Low Threshold", "Video2", &slideposisirendah, maxrendahtreshold, onLowThresholdSlide);
 
	// Create the high threshold slider
   	//cvCreateTrackbar("High Threshold", "Video2", &slideposisitinggi, maxtinggitreshold, onHighThresholdSlide);
	 settingWindows();
	 cvNamedWindow("Konfigurasi");
     cvNamedWindow("Video");
     cvNamedWindow("Video2",CV_WINDOW_AUTOSIZE);

	 //mengulangi  setiap frame dari video
      while(true){

            frame = cvQueryFrame(capture);           
            if(!frame) break;
            frame=cvCloneImage(frame); 
            
            cvSmooth(frame, frame, CV_GAUSSIAN,3,3);//menghaluskan gambar yg asli menggunakan kernel Gaussian

            IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
            cvCvtColor(frame, imgHSV, CV_BGR2HSV); //merubah format warna RGB ke Grayscale
            IplImage* imgThresh = GetThresholdedImage(imgHSV);
          
            cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3);//menghaluskan gambar biner menggunakan kernel gaussian
            
			//membuat posisi jalur objek
           trackObject(imgThresh);

		   //Menambahkan jalur gambar dan frame
           cvAdd(frame, imgTracking, frame);

           cvShowImage("Video", imgThresh);           
           cvShowImage("Video2", frame);
           
       
           cvReleaseImage(&imgHSV);
           cvReleaseImage(&imgThresh);            
           cvReleaseImage(&frame);

            int c = cvWaitKey(10);
            
            if((char)c==27 ) break;      
      }

      cvDestroyAllWindows() ;
      cvReleaseImage(&imgTracking);
      cvReleaseCapture(&capture);     

      return 0;
}
示例#11
0
void Calibrator::on_camaraButton_clicked()
{

        if(capturing)
        {
        while(true)
            {
                // Will hold a frame captured from the camera
                frame = 0;
                frame = cvQueryFrame(capture);
                // If we couldn't grab a frame... quit
                if(!frame) break;
                // If this is the first frame, we need to initialize it
//                if(imgScribble == NULL)
//                {
//                    imgScribble = cvCreateImage(cvGetSize(frame), 8, 3);
//                }
//                // Holds the yellow thresholded image (yellow = white, rest = black)
                IplImage* imgGreenThresh = GetThresholdedImage(frame);
                // Calculate the moments to estimate the position of the ball
                CvMoments *moments = (CvMoments*)malloc(sizeof(CvMoments));
                cvMoments(imgGreenThresh, moments, 1);

                // The actual moment values
                double moment10 = cvGetSpatialMoment(moments, 1, 0);
                double moment01 = cvGetSpatialMoment(moments, 0, 1);
                double area = cvGetCentralMoment(moments, 0, 0);

                // Holding the last and current ball positions
                static int posX = 0;
                static int posY = 0;

//                int lastX = posX;
//                int lastY = posY;

                posX = moment10/area;
                posY = moment01/area;

                // Print it out for debugging purposes
//                printf("position (%d,%d)\n", posX, posY);
                playerPos = QPoint(posX, posY);
                QString str = "( " + QString::number(posX) + " , " + QString::number(posY) + " ) ";
                ui->positionLabel->setText(str);

                // We want to draw a line only if its a valid position
//                if(lastX>0 && lastY>0 && posX>0 && posY>0)
//                {
//                    // Draw a yellow line from the previous point to the current point
//                    cvLine(imgScribble, cvPoint(posX, posY), cvPoint(lastX, lastY), cvScalar(0,255,255), 5);
//                }

//                // Add the scribbling image and the frame...
//                        cvAdd(frame, imgScribble, frame);
                        cvShowImage("threshold", imgGreenThresh);
                        cvShowImage("video", frame);

                // Wait for a keypress
                        int c = cvWaitKey(10);
                        if(c!=-1)
                        {
                            // If pressed, break out of the loop
                            cvDestroyWindow("threshold");
                            cvDestroyWindow("video");
                            break;
                        }

                        // Release the thresholded image+moments... we need no memory leaks.. please
                                cvReleaseImage(&imgGreenThresh);
                                delete moments;
            }
        // We're done using the camera. Other applications can now use it
            //cvReleaseCapture(&capture);
            //cvReleaseWindow?();
        }
}
示例#12
0
int main(){

		IplImage* frame = 0;
		frame = cvQueryFrame(capture);

		// If we couldn't grab a frame... quit
		        if(!frame)
		            break;

            if (imgScribble == NULL) {
                imgScribble = cvCreateImage(cvGetSize(frame), 8, 3);
            }

            // Holds the color thresholded image (color = white, rest = black)
            IplImage* imgYellowThresh = GetThresholdedImage(frame, 4);
            IplImage* imgGreenThresh = GetThresholdedImage(frame, 1);
            IplImage* imgBlueThresh = GetThresholdedImage(frame, 2);
            IplImage* imgRedThresh = GetThresholdedImage(frame, 3);

            // Calculate the moments to estimate the position of the ball
            CvMoments *moments_yellow = (CvMoments*) malloc(sizeof(CvMoments));
            CvMoments *moments_green = (CvMoments*) malloc(sizeof(CvMoments));
            CvMoments *moments_blue = (CvMoments*) malloc(sizeof(CvMoments));
            CvMoments *moments_red = (CvMoments*) malloc(sizeof(CvMoments));

            cvMoments(imgYellowThresh, moments_yellow, 1);
            cvMoments(imgGreenThresh, moments_green, 1);
            cvMoments(imgBlueThresh, moments_blue, 1);
            cvMoments(imgRedThresh, moments_red, 1);

            // The actual moment values
            double moment10y = cvGetSpatialMoment(moments_yellow, 1, 0);
            double moment01y = cvGetSpatialMoment(moments_yellow, 0, 1);
            double areay = cvGetCentralMoment(moments_yellow, 0, 0);

            double moment10g = cvGetSpatialMoment(moments_green, 1, 0);
            double moment01g = cvGetSpatialMoment(moments_green, 0, 1);
            double areag = cvGetCentralMoment(moments_green, 0, 0);

            double moment10b = cvGetSpatialMoment(moments_blue, 1, 0);
            double moment01b = cvGetSpatialMoment(moments_blue, 0, 1);
            double areab = cvGetCentralMoment(moments_blue, 0, 0);

            double moment10r = cvGetSpatialMoment(moments_red, 1, 0);
            double moment01r = cvGetSpatialMoment(moments_red, 0, 1);
            double arear = cvGetCentralMoment(moments_red, 0, 0);

            //* Yellow processing    *//
            // Holding the last and current color positions
            static int posXy = 0;
            static int posYy = 0;

            lastXy = posXy;
            lastYy = posYy;

            int tempXy = moment10y / areay;
            int tempYy = moment01y / areay;

            if ( tempXy >= 0 && tempYy >= 0  && tempXy < 700 && tempYy < 700 && areay>1000 ){
            posXy = moment10y / areay;
            posYy = moment01y / areay;
            }

            

            // Print it out for debugging purposes
            std::cout << std::endl;
            printf("position yellow (%d,%d)\n", posXy, posYy);
            std::cout  <<"area yellow : "<< areay  << std::endl;

            //* Green Processing    *//
            static int posXg = 0;
            static int posYg = 0;

            lastXg = posXg;
            lastYg = posYg;

            int tempXg = moment10g / areag;
            int tempYg = moment01g / areag;

            if ( tempXg >= 0 && tempYg >= 0  && tempXg < 700 && tempYg < 700 && areag>1000 ){
            posXg = moment10g / areag;
            posYg = moment01g / areag;
            }

            

            // Print it out for debugging purposes
            printf("position green (%d,%d)\n", posXg, posYg);
            std::cout  <<"area green : "<< areag  << std::endl;


            static int posXb = 0;
            static int posYb = 0;

            lastXb = posXb;
            lastYb = posYb;

            int tempXb = moment10b / areab;
            int tempYb = moment01b / areab;

            if ( tempXb >= 0 && tempYb >= 0  && tempXb < 700 && tempYb < 700 && areab>700 ){
            posXb = moment10b / areab;
            posYb = moment01b / areab;
            }
            

            // Print it out for debugging purposes
            printf("position blue (%d,%d)\n", posXb, posYb);
            std::cout  <<"area blue : "<< areab  << std::endl;


            static int posXr = 0;
            static int posYr = 0;

            lastXr = posXr;
            lastYr = posYr;

            int tempXr = moment10r / arear;
            int tempYr = moment01r / arear;

            if ( tempXr >= 0 && tempYr >= 0  && tempXr < 700 && tempYr < 700 && arear>1000 ){
            posXr = moment10r / arear;
            posYr = moment01r / arear;
            }


            printf("position red (%d,%d)\n", posXr, posYr);
            std::cout  <<"area red : "<< arear  << std::endl;




            // We want to draw a line only if its a valid position
            if (lastXy > 0 && lastYy > 0 && posXy > 0 && posYy > 0 && lastXy < 700 && lastYy < 700 && posXy < 700 && posYy < 700) {
                // Draw a line from the previous point to the current point
                cvLine(imgScribble, cvPoint(posXy, posYy), cvPoint(lastXy,
                        lastYy), cvScalar(0, 255, 255), 5);
            }

            if (lastXg > 0 && lastYg > 0 && posXg > 0 && posYg > 0 && lastXg < 700 && lastYg < 700 && posXg < 700 && posYg < 700) {
                cvLine(imgScribble, cvPoint(posXg, posYg), cvPoint(lastXg,
                        lastYg), cvScalar(0, 255, 0), 5);
            }

            if (lastXb > 0 && lastYb > 0 && posXb > 0 && posYb > 0 && lastXb < 700 && lastYb < 700 && posXb < 700 && posYb < 700) {
                cvLine(imgScribble, cvPoint(posXb, posYb), cvPoint(lastXb,
                        lastYb), cvScalar(255, 0, 0), 5);
            }

            if (lastXr > 0 && lastYr > 0 && posXr > 0 && posYr > 0 && lastXr < 700 && lastYr < 700 && posXr < 700 && posYr < 700) {
                cvLine(imgScribble, cvPoint(posXr, posYr), cvPoint(lastXr,
                        lastYr), cvScalar(0, 0, 255), 5);
            }

            // Add the scribbling image and the frame... and we get a combination of the 4
            cvAdd(frame, imgScribble, frame);
            cvShowImage("thresh yellow", imgYellowThresh);
            cvShowImage("thresh green", imgGreenThresh);
            cvShowImage("thresh blue", imgBlueThresh);
            cvShowImage("thresh red", imgRedThresh);
            cvShowImage("video", frame);



            // Release the thresholded image
            cvReleaseImage(&imgYellowThresh);
            cvReleaseImage(&imgGreenThresh);
            cvReleaseImage(&imgBlueThresh);
            cvReleaseImage(&imgRedThresh);

            delete moments_yellow;
            delete moments_green;
            delete moments_blue;
            delete moments_red;

            cvShowImage("video", frame);

        }
示例#13
0
int main(){
  
////////////////////GAME PROPERTIES///////////////////////////////////

	//window properties
	sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "Tungu");
	pong.setMouseCursorVisible(false);
	pong.setFramerateLimit(60);

	//music
	sf::Music bgm;
	bgm.openFromFile("multimedia/audio/background.wav");
	bgm.setPitch(1.5);
	bgm.setLoop(true);
	bgm.play();

	//sound
	sf::SoundBuffer buffer1;
	buffer1.loadFromFile("multimedia/audio/bounce.wav");
	sf::Sound bounce;
	bounce.setBuffer(buffer1);
	sf::SoundBuffer buffer2;
	buffer2.loadFromFile("multimedia/audio/point.wav");
	sf::Sound point;
	point.setBuffer(buffer2);
	
	//ncp properties
	sf::RectangleShape ncp(sf::Vector2f(5, RENDERHEIGHT / 1.6));
	ncp.setFillColor(sf::Color(50, 50, 50));
	ncp.setPosition(RENDERWIDTH / 2, RENDERHEIGHT / 2 - (RENDERHEIGHT / 1.6) / 2 );

	//player 1 properties
	int p1Len = 100;
	sf::RectangleShape player1(sf::Vector2f(15, p1Len));
	player1.setFillColor(sf::Color(0, 0, 255));
	player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2);
	int player1Score = 0;

	//player 2 properties
	int p2Len = 100;
	sf::RectangleShape player2(sf::Vector2f(15, p2Len));
	player2.setFillColor(sf::Color(0, 255, 0));
	player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2);
	int player2Score = 0;

	//ball properties
	sf::CircleShape ball(10, 25);
	ball.setFillColor(sf::Color(255, 255, 255));
	ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius());
	float BALLSPEED = 15;
	float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED;
	float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius();
	float ballDiameter = ball.getRadius() * 2;
	
	//score-timer text
	sf::Font font;
	font.loadFromFile("fonts/LiberationSerif-Regular.ttf");
	sf::Text score1("0", font, 80);
	score1.setPosition(RENDERWIDTH / 4, 0);
	sf::Text score2("0", font, 80);
	score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);
	sf::Text timer1("", font, 50);
	timer1.setPosition(0 , 5 * RENDERHEIGHT / 6);
	sf::Text timer2("", font, 50);
	timer2.setPosition(RENDERWIDTH / 2 - timer2.getLocalBounds().width, 5 * RENDERHEIGHT / 6);
	int time1 = 0;
	int time2 = 0;
	
	//gameover
	sf::Text gameover("GAME OVER", font, 120);
	gameover.setColor(sf::Color::Red);
	gameover.setPosition(0, RENDERHEIGHT / 3);
	
		
	///////////////CAMERA FUNTIONS//////////////////////

      CvCapture* capture =0;   
    
      capture = cvCaptureFromCAM(0);


     	 if(!capture){

		printf("Capture failure\n");

		return -1;
      }
      
      IplImage* frame=0;

      frame = cvQueryFrame(capture);  
         
      if(!frame) return -1;
  
     //create a blank image and assigned to 'imgTracking' which has the same size of original video

     imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);

     cvZero(imgTracking); //covert the image, 'imgTracking' to black

     //cvNamedWindow("Player1"); 
    
     ///cvNamedWindow("Player2");

      //iterate through each frames of the video
     
      while(player1Score + player2Score != 7){

		frame = cvQueryFrame(capture); 
          
		if(!frame) break;

		frame=cvCloneImage(frame); 
            
		cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

			/////////////////// Player 1 ////////////////////

			IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 

			cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV

			IplImage* imgThresh = GetThresholdedImage(imgHSV, 85, 143, 40, 116, 256, 159); //guante cyan
	 
			cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel
	    
			player100 =  trackObject(imgThresh, 255, 0, 0, 1);

			/////////////////// Player 2 ////////////////////

			IplImage* imgHSV2 = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
	    
			cvCvtColor(frame, imgHSV2, CV_BGR2HSV);//Change the color format from BGR to HSV

			IplImage* imgThresh2 = GetThresholdedImage(imgHSV2, 26, 145, 31, 73, 256, 111); //guante verde

 			cvSmooth(imgThresh2, imgThresh2, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel

			player200 = trackObject(imgThresh2, 0, 255, 0, 2);

            	// Add the tracking image and the frame

		cvAdd(frame, imgTracking, frame);

		//cvShowImage("Player1", imgThresh);
 
		//cvShowImage("Player2", imgThresh2); 
		
		cvMoveWindow("Video", 1800, 0);

		cvResizeWindow("Video", 100, 240);
           
		cvShowImage("Video", frame);
           
           //Clean up used images

           cvReleaseImage(&imgHSV);

	   cvReleaseImage(&imgHSV2);

           cvReleaseImage(&imgThresh);

	   cvReleaseImage(&imgThresh2);   
          
           cvReleaseImage(&frame);

            //Wait 10mS
            int c = cvWaitKey(10);

            //If 'ESC' is pressed, break the loop
            if((char)c==27 ) break;  


/////////////////////////////Scores///////////////////////////////////

		//score for player one winning
		if(player1Score == player2Score + 1)
		{
		    timer1.setString(convertInt(time1 += 2));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 2)
		{
		    timer1.setString(convertInt(time1 += 4));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 3)
		{
		    timer1.setString(convertInt(time1 += 8));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 4)
		{
		    timer1.setString(convertInt(time1 += 16));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 5)
		{
		    timer1.setString(convertInt(time1 += 32));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 6)
		{
		    timer1.setString(convertInt(time1 += 64));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		//score on equals
		if(player1Score == player2Score)
		{
		    timer1.setString(convertInt(time1 += 1));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		//score for player two winning
		if(player2Score == player1Score + 1)
		{
		    timer2.setString(convertInt(time2 += 2));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 2)
		{
		    timer2.setString(convertInt(time2 += 4));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 3)
		{
		    timer2.setString(convertInt(time2 += 8));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 4)
		{
		    timer2.setString(convertInt(time2 += 16));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 5)
		{
		    timer2.setString(convertInt(time2 += 32));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 6)
		{
		    timer2.setString(convertInt(time2 += 64));
		    timer1.setString(convertInt(time1 += 1));
		}

//////////////////////////////Game////////////////////////////////////

		//player 1 movement muy lento
		
		if(player100==6)
			
			player1.move(0, -(vel-3));

		else if(player100==-6)

			player1.move(0, vel-3);

		//player 1 movement LENTO	
		
		if(player100==1)
			
			player1.move(0, -vel);

		else if(player100==-1)

			player1.move(0, vel);


		//player 1 movement MEDIO
		
		if(player100==2)
			
			player1.move(0, -(vel+10));

		else if(player100==-2)

			player1.move(0, vel+10);

		//player 1 movement RAPIDO
		
		if(player100==3)
			
			player1.move(0, -(vel+20));

		else if(player100==-3)

			player1.move(0, vel+20);

		//player 1 movement muy rapido
		
		if(player100==4)
			
			player1.move(0, -(vel+25));

		else if(player100==-4)

			player1.move(0, vel+25);

		//player 1 movement Extreme
		
		if(player100==5)
			
			player1.move(0, -(vel+30));

		else if(player100==-5)

			player1.move(0, vel+30);

		
		//MOVIMIENTO GOLPE PLAYER1

		if(player100==0)

			player1.move(0,0);
			
		
	
		if (player1.getPosition().x <= 10){

		if(player100==22)
			
			player1.move(10, 0);
			
			
		}


		//player 2 movement muy LENTO

		if(player200==6)

			player2.move(0, -(vel-3));

		else if(player200==-6)

			player2.move(0, vel-3);

		//player 2 movement LENTO

		if(player200==1)

			player2.move(0, -vel);

		else if(player200==-1)

			player2.move(0, vel);

		//player 2 movement MEDIO

		if(player200==2)

			player2.move(0, -(vel+10));

		else if(player200==-2)

			player2.move(0, vel+10);

		//player 2 movement RAPIDO

		if(player200==3)

			player2.move(0, -(vel+20));

		else if(player200==-3)

			player2.move(0, vel+20);

		//player 2 movement muy rapido

		if(player200==4)

			player2.move(0, -(vel+25));

		else if(player200==-4)

			player2.move(0, vel+25);

		//player 2 movement Extreme

		if(player200==5)
			player2.move(0, -(vel+30));

		else if(player200==-5)

			player2.move(0, vel+30);

		
		if(player200==0) 

			player2.move(0,0);

		//MOVIMIENTO GOLPE PLAYER2
		
		if (player2.getPosition().x >= RENDERWIDTH-player2.getSize().x-10){
			  
		if(player200==-22)
			
			player2.move(-10, 0);
			
			
		}

		//player 1 and wall collision

		if(player1.getPosition().y <= 0)

			player1.setPosition(0, 0);

		if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y)

			player1.setPosition(0, RENDERHEIGHT - player1.getSize().y);

		//PLAYER1 AND WALL BACK COLLISION

		if(player1.getPosition().x != 0)

			player1.move(-1,0);
		
		//PLAYER2 AND WALL BACK COLLISION

		if(player2.getPosition().x != RENDERWIDTH-player2.getSize().x)

			player2.move(1,0);
		
		//player 2 and wall collision

		if(player2.getPosition().y <= 0)

			player2.setPosition(RENDERWIDTH - player2.getSize().x, 0);

		if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y)

			player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y);

		//ball and wall collision

		if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter){


			ballVelY *= -1;

			bounce.play();

		}

		//ball and player 1 collision

		if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x){


			if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y) || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y && ball.getPosition().y >= player1.getPosition().y){


	if (player1.getPosition().x > 14){

				ballVelX = (ballVelX - 5) * -1;

				ball.setFillColor(sf::Color(255,0,0));

				
			}

	else if (player1.getPosition().x <= 14){

				ballVelX = (ballVelX - 3) * -1;

				ball.setFillColor(sf::Color(0,0,255));

				bounce.play();
}
			

			}

			else{
				ball.setFillColor(sf::Color(255,255,255));

				point.play();

				player2Score += 1;  

				ballX = RENDERWIDTH / 2 - ball.getRadius();

				if (BALLSPEED < 8)

					BALLSPEED += 0.2;

				ballVelX = BALLSPEED;

				score2.setString(convertInt(player2Score));

				score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);

				if (p2Len > 40)

					p2Len -= 10;

				player2.setSize(sf::Vector2f(15, p2Len));

				if (p1Len < 100)

					p1Len += 10;

				player1.setSize(sf::Vector2f(15, p1Len));
				
			}
		}

		//ball and player 2 collision

		if (ball.getPosition().x + ballDiameter >= player2.getPosition().x){

		
			if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y) || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y && ball.getPosition().y >= player2.getPosition().y){
			


				if (player2.getPosition().x < (RENDERWIDTH-9-player2.getSize().x)){

					ballVelX = (ballVelX + 5) * -1;

					ball.setFillColor(sf::Color(255,0,0));

					
				
				}

				else if (player2.getPosition().x >= (RENDERWIDTH-9-player2.getSize().x)){

					ballVelX = (ballVelX + 3) * -1;

					ball.setFillColor(sf::Color(0,255,0));

					bounce.play();
			}
		}
				
			
				else{
			
					ball.setFillColor(sf::Color(255,255,255));

					point.play();

					player1Score += 1;

					ballX = RENDERWIDTH / 2 - ball.getRadius();

					if (BALLSPEED < 8)

						BALLSPEED += 0.5;

					ballVelX = -BALLSPEED;

					score1.setString(convertInt(player1Score));

					if (p1Len > 40)
						p1Len -= 10;

					player1.setSize(sf::Vector2f(15, p1Len));

					if (p2Len < 100)

						p2Len += 10;

					player2.setSize(sf::Vector2f(15, p2Len));
			}
		}

		//ball position update
		ballX += ballVelX;
		ballY += ballVelY;
		ball.setPosition(ballX, ballY);

		//render updates
		
		pong.clear();
		pong.draw(score1);
		pong.draw(timer1);
		pong.draw(timer2);
		pong.draw(score2);
		pong.draw(player1);
		pong.draw(player2);
		pong.draw(ball);
		pong.draw(ncp);
		pong.display();


		while(player1Score + player2Score == 7){

			if(player1Score > player2Score)
				timer1.setString(convertInt(time1 += 500));
			if(player1Score < player2Score)
				timer2.setString(convertInt(time2 += 500));
		
			pong.clear(sf::Color::Black);
			pong.draw(score1);
			pong.draw(timer1);
			pong.draw(timer2);
			pong.draw(score2);
			pong.draw(gameover);
			pong.display();

			counter(3);
			break;
		}

/////////////////////Finish Game/////////////////////////////////


    
      }

	std::stringstream ss;
	ss.str (timer1.getString());
	std::string scorePlayer1 = ss.str();
	ss.str (timer2.getString());
	std::string scorePlayer2 = ss.str();
	std::cout << "Final Score:" << '\n';
	std::cout << "Player1: " + scorePlayer1 << '\n';
	std::cout << "Player2: " + scorePlayer2 << '\n';

	
	std::ofstream myfile ("highscores.txt", std::ofstream::in | std::ofstream::out | std::ofstream::app);
  	if (myfile.is_open())
  	{
  		myfile << scorePlayer1 << std::endl;
    		myfile << scorePlayer2 << std::endl;
    		myfile.close();
  	}

  	else std::cout << "Unable to open file";

      cvDestroyAllWindows() ;
      cvReleaseImage(&imgTracking);
      cvReleaseCapture(&capture);     

      return 0;
}
示例#14
0
int main() {
	raspicam::RaspiCam_Cv Camera; // Camera Object
	cv::Mat frame;

	// Set camera params
	Camera.set(CV_CAP_PROP_FORMAT, CV_8UC3); // For color
	Camera.set(CV_CAP_PROP_FRAME_WIDTH, 640);
	Camera.set(CV_CAP_PROP_FRAME_HEIGHT, 480);

	// Open camera
    std::cout << "Opening camera...\n";
    if (! Camera.open()) {
    	std::cerr << "Error opening camera!\n";
    	return -1;
    }


	// The two windows we'll be using
  cvNamedWindow("video");
	cvNamedWindow("thresh");

	cvMoveWindow("video", 0, 0);
	cvMoveWindow("thresh", 240, 0);

	int thresh_h[] {0, 18};
	int thresh_s[] {160, 255};
	int thresh_v[] {144, 255};
	const int max_thresh(255);

	cv::createTrackbar(" H min:", "thresh", &thresh_h[0], max_thresh, nullptr);
	cv::createTrackbar(" H max:", "thresh", &thresh_h[1], max_thresh, nullptr);
	cv::createTrackbar(" S min:", "thresh", &thresh_s[0], max_thresh, nullptr);
	cv::createTrackbar(" S max:", "thresh", &thresh_s[1], max_thresh, nullptr);
	cv::createTrackbar(" V min:", "thresh", &thresh_v[0], max_thresh, nullptr);
	cv::createTrackbar(" V max:", "thresh", &thresh_v[1], max_thresh, nullptr);

	// This image holds the "scribble" data, the tracked positions of the ball
	IplImage* imgScribble = NULL;

	cv::Mat frame_mat;

	while (true) {
		if (! Camera.grab()) {
			break;
		}
		Camera.retrieve(frame_mat);

		// Will hold a frame captured from the camera
		IplImage frame = frame_mat;

		// If this is the first frame, we need to initialize it
		if (imgScribble == NULL) {
			imgScribble = cvCreateImage(cvGetSize(&frame), 8, 3);
		}

		// Holds the yellow thresholded image (yellow = white, rest = black)
		IplImage* imgYellowThresh = GetThresholdedImage(&frame, thresh_h, thresh_s, thresh_v);

		// Calculate the moments to estimate the position of the ball
		CvMoments moments;
		cvMoments(imgYellowThresh, &moments, 1);

		// The actual moment values
		double moment10 = cvGetSpatialMoment(&moments, 1, 0);
		double moment01 = cvGetSpatialMoment(&moments, 0, 1);
		double area = cvGetCentralMoment(&moments, 0, 0);

		// Holding the last and current ball positions
		static int posX = 0;
		static int posY = 0;

		int lastX = posX;
		int lastY = posY;

		posX = moment10 / area;
		posY = moment01 / area;

		// Print it out for debugging purposes
		printf("position (%d,%d)\n", posX, posY);

		// We want to draw a line only if its a valid position
		if (lastX > 0 && lastY > 0 && posX > 0 && posY > 0) {
			// Draw a yellow line from the previous point to the current point
			cvLine(imgScribble, cvPoint(posX, posY), cvPoint(lastX, lastY), cvScalar(0,255,255), 5);
		}

		// Add the scribbling image and the frame... and we get a combination of the two
		cvAdd(&frame, imgScribble, &frame);
		cvCvtColor(&frame, &frame, CV_BGR2RGB);
		cvShowImage("video", &frame);
//	cvShowImage("video", imgScribble);
		cvShowImage("thresh", imgYellowThresh);

		// Wait for a keypress
		int c = cvWaitKey(10);
		if (c != -1) {
			// If pressed, break out of the loop
      break;
		}
  }

  return 0;
}
示例#15
0
int main(){
  
////////////////////GAME PROPERTIES///////////////////////////////////

//window properties
	sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "GameName");
	pong.setMouseCursorVisible(false);
	pong.setFramerateLimit(60);

	//music
	sf::Music bgm;
	bgm.openFromFile("musica.wav");
	bgm.setPitch(1.5);
	bgm.setLoop(true);
	bgm.play();

	//sound
	sf::SoundBuffer buffer1;
	buffer1.loadFromFile("/usr/lib/libreoffice/share/gallery/sounds/beam.wav");
	sf::Sound bounce;
	bounce.setBuffer(buffer1);
	sf::SoundBuffer buffer2;
	buffer2.loadFromFile("/usr/lib/libreoffice/share/gallery/sounds/beam2.wav");
	sf::Sound point;
	point.setBuffer(buffer2);	
	sf::SoundBuffer buffer3;
	buffer3.loadFromFile("/usr/lib/libreoffice/share/gallery/sounds/beam.wav"); //perfecti hit!!!!!
	sf::Sound perfecthit;
	perfecthit.setBuffer(buffer3);

	//player 1 properties
	int p1Len = 80;
	sf::RectangleShape player1(sf::Vector2f(15, p1Len));
	player1.setFillColor(sf::Color(0, 0, 255));
	player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2);
	int player1Score = 0;
	

	//player 2 properties
	int p2Len = 80;
	sf::RectangleShape player2(sf::Vector2f(15, p2Len));
	player2.setFillColor(sf::Color(0, 255, 0));
	player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2);
	int player2Score = 0;
	

	//ball properties
	sf::CircleShape ball(7, 25);
	ball.setFillColor(sf::Color(255,255,255));
	ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius());
	float BALLSPEED = 2;
	float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED;
	float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius();
	float ballDiameter = ball.getRadius() * 2;
	
	sf::Font font;

	font.loadFromFile("/usr/share/cups/fonts/FreeMonoOblique.ttf");

	font.loadFromFile("/usr/share/fonts/truetype/ttf-liberation/LiberationSerif-Bold.ttf");

	sf::Text score1("0", font, 80);
	score1.setPosition(RENDERWIDTH / 4, 0);
	sf::Text score2("0", font, 80);
	score2.setPosition(3 * RENDERWIDTH / 4, 0);
	
///////////////FINISH PROPERTIES//////////////////////////////////////////////////////



      CvCapture* capture =0;       
      capture = cvCaptureFromCAM(1);
      if(!capture){
printf("Capture failure\n");
return -1;
      }
      
      IplImage* frame=0;
      frame = cvQueryFrame(capture);           
      if(!frame) return -1;
  
     //create a blank image and assigned to 'imgTracking' which has the same size of original video
     imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);

     cvZero(imgTracking); //covert the image, 'imgTracking' to black

     cvNamedWindow("Video");     
     cvNamedWindow("Ball");

      //iterate through each frames of the video     
      while(true){

            frame = cvQueryFrame(capture);           
            if(!frame) break;
            frame=cvCloneImage(frame); 
            
           cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 

            cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV

IplImage* imgThresh = GetThresholdedImage(imgHSV, 94, 169, 127, 143, 251, 229);
	    
	     cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel
	     
	   player100 =  trackObject(imgThresh, 255, 0, 0, 1);

	     
          	
IplImage* imgHSV2 = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
	    
	      cvCvtColor(frame, imgHSV2, CV_BGR2HSV);

IplImage* imgThresh2 = GetThresholdedImage(imgHSV2, 22, 64, 152, 50, 134, 256);

 		cvSmooth(imgThresh2, imgThresh2, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel

		player200 = trackObject(imgThresh2, 0, 255, 0, 2);

            // Add the tracking image and the frame

          cvAdd(frame, imgTracking, frame);

          cvShowImage("Ball", imgThresh); 
	  cvShowImage("Ball2", imgThresh2);            
          cvShowImage("Video", frame);
           
           //Clean up used images
           cvReleaseImage(&imgHSV);
	   cvReleaseImage(&imgHSV2);
           cvReleaseImage(&imgThresh);
	   cvReleaseImage(&imgThresh2);             
           cvReleaseImage(&frame);

            //Wait 10mS
            int c = cvWaitKey(10);
            //If 'ESC' is pressed, break the loop
            if((char)c==27 ) break;  


//////////////////////////////Game////////////////////////////////////

//player 1 movement
		
		if(player100==1){
			
			player1.move(0, -10);}

		else if(player100==-1){

			player1.move(0, 10);

		}
		//MOVIMIENTO GOLPE PLAYER1

		if(player100==0){ player1.move(0,0);}
	
		if (player1.getPosition().x <= 10){
		if(player100==2){
			
			player1.move(10, 0);
			
			
		}}

		//player 2 movement

		if(player200==1)
			player2.move(0, -10);
		else if(player200==-1)
			player2.move(0, 10);
		
		if(player200==0){ player2.move(0,0);}

		//MOVIMIENTO GOLPE PLAYER2
			
		if (player2.getPosition().x >= RENDERWIDTH-player2.getSize().x-10){
			  
		if(player200==-2){
			
			player2.move(-10, 0);
			
			
		}}

		//player 1 and wall collision
		if(player1.getPosition().y <= 0)
			player1.setPosition(0, 0);
		if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y)
			player1.setPosition(0, RENDERHEIGHT - player1.getSize().y);

		//PLAYER1 AND WALL BACK COLLISION
		if(player1.getPosition().x != 0)
			player1.move(-1,0);
		
		//PLAYER2 AND WALL BACK COLLISION
		if(player2.getPosition().x != RENDERWIDTH-player2.getSize().x)
			player2.move(1,0);
		
		//player 2 and wall collision
		if(player2.getPosition().y <= 0)
			player2.setPosition(RENDERWIDTH - player2.getSize().x, 0);
		if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y)
			player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y);

		//ball and wall collision
		if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter)
		{
			ballVelY *= -1;
			bounce.play();
		}

		//ball and player 1 collision
		if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x)
		{
			if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y) || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y && ball.getPosition().y >= player1.getPosition().y){


	if (player1.getPosition().x > 14){

				ballVelX = (ballVelX - 2) * -1;
				ball.setFillColor(sf::Color(255,0,0));
				perfecthit.play();
		
			}

	else if (player1.getPosition().x <= 14){

				ballVelX = (ballVelX - 1) * -1;
				ball.setFillColor(sf::Color(0,0,255));
				bounce.play();
}
			

			}

			else
			{
ball.setFillColor(sf::Color(255,255,255));
				point.play();
				player2Score += 1;  
				ballX = RENDERWIDTH / 2 - ball.getRadius();
				if (BALLSPEED < 8){
					BALLSPEED += 0.2;
					}
				ballVelX = BALLSPEED;
				score2.setString(convertInt(player2Score));
				score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);

				if (p2Len > 40)
					p2Len -= 10;
				player2.setSize(sf::Vector2f(15, p2Len));
				if (p1Len < 100)
					p1Len += 10;
				player1.setSize(sf::Vector2f(15, p1Len));
				
			}
		}

		//ball and player 2 collision
		if (ball.getPosition().x + ballDiameter >= player2.getPosition().x)
		{
			if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y) || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y && ball.getPosition().y >= player2.getPosition().y)
			{


	if (player2.getPosition().x < (RENDERWIDTH-9-player2.getSize().x)){

				ballVelX = (ballVelX + 2) * -1;
				ball.setFillColor(sf::Color(255,0,0));
				perfecthit.play();
				
			
			}

	else if (player2.getPosition().x >= (RENDERWIDTH-9-player2.getSize().x)){

				ballVelX = (ballVelX + 1) * -1;
				ball.setFillColor(sf::Color(0,255,0));
				bounce.play();
			}
		}
				
			
			else
			{
ball.setFillColor(sf::Color(255,255,255));
				point.play();
				player1Score += 1;
				ballX = RENDERWIDTH / 2 - ball.getRadius();
				if (BALLSPEED < 8)
					BALLSPEED += 0.5;
				ballVelX = -BALLSPEED;
				score1.setString(convertInt(player1Score));
				if (p1Len > 40)
					p1Len -= 10;
				player1.setSize(sf::Vector2f(15, p1Len));
				if (p2Len < 100)
					p2Len += 10;
				player2.setSize(sf::Vector2f(15, p2Len));
			}
		}

		//ball position update
		ballX += ballVelX;
		ballY += ballVelY;
		ball.setPosition(ballX, ballY);

		//render updates
		pong.clear();
		pong.draw(score1);
		pong.draw(score2);
	
		pong.draw(player1);
		pong.draw(player2);
		pong.draw(ball);
		pong.display();

/////////////////////Finish Game/////////////////////////////////


    
      }

      cvDestroyAllWindows() ;
      cvReleaseImage(&imgTracking);
      cvReleaseCapture(&capture);     

      return 0;
}
示例#16
0
int main()
{
	//window properties
	sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "GameName"); //, sf::Style::Fullscreen
	pong.setMouseCursorVisible(false);
	pong.setFramerateLimit(24);
/*
	//music
	sf::Music bgm;
	bgm.openFromFile("musica.wav");
	bgm.setPitch(1.5);
	bgm.setLoop(true);
	bgm.play();
*/
	//sound 

	sf::SoundBuffer buffer1;
	buffer1.loadFromFile("/usr/lib/libreoffice/share/gallery/sounds/beam.wav");
	sf::Sound bounce;
	bounce.setBuffer(buffer1);
	sf::SoundBuffer buffer2;
	buffer2.loadFromFile("/usr/lib/libreoffice/share/gallery/sounds/beam2.wav");
	sf::Sound point;
	point.setBuffer(buffer2);	
	sf::SoundBuffer buffer3;
	buffer3.loadFromFile("/usr/lib/libreoffice/share/gallery/sounds/beam.wav"); //perfecti hit!!!!!
	sf::Sound perfecthit;
	perfecthit.setBuffer(buffer3);


	//player 1 properties
	int p1Len = 80;
	sf::RectangleShape player1(sf::Vector2f(15, p1Len));
	player1.setFillColor(sf::Color(0, 0, 255));
	player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2);
	int player1Score = 0;
	

	//player 2 properties
	int p2Len = 80;
	sf::RectangleShape player2(sf::Vector2f(15, p2Len));
	player2.setFillColor(sf::Color(0, 255, 0));
	player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2);
	int player2Score = 0;
	

	//ball properties
	sf::CircleShape ball(7, 25);
	ball.setFillColor(sf::Color(255,255,255));
	ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius());
	float BALLSPEED = 2;
	float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED;
	float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius();
	float ballDiameter = ball.getRadius() * 2;

	sf::Font font;

	font.loadFromFile("/usr/share/cups/fonts/FreeMonoOblique.ttf");

	font.loadFromFile("/usr/share/fonts/truetype/ttf-liberation/LiberationSerif-Bold.ttf");

	sf::Text score1("0", font, 80);
	score1.setPosition(RENDERWIDTH / 4, 0);
	sf::Text score2("0", font, 80);
	score2.setPosition(3 * RENDERWIDTH / 4, 0);
	
	//game loop
	//while(pong.isOpen())

/////////////////////Declaraciones////////////////////////////////


IplImage* frame=0;
IplImage* imgTracking;
CvCapture* capture =0; 

IplImage* imgThresh;
IplImage* imgThresh2;
sf::Event event;
int player100=0;
int player200=0;


 capture = cvCaptureFromCAM(1);


	for(int i=0;i<1000;++i)
	{
		

   		  if(!capture){
			printf("Capture failure\n");
				return -1;
      			}
      
      
      frame = cvRetrieveFrame(capture); 
          
      if(!frame) return -1;
  
     //create a blank image and assigned to 'imgTracking' which has the same size of original video
     imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);
            

           cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

	IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 

            cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV

	imgThresh = GetThresholdedImage(imgHSV, 24, 0, 224, 46, 89, 256);

	cvReleaseImage(&imgHSV);
	delete(imgHSV);
	    
	     cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel
	     
	     player100 = trackObject(imgThresh, 255, 0, 0, 1);

	     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
          	


	IplImage* imgHSV2 = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
	    
	      cvCvtColor(frame, imgHSV2, CV_BGR2HSV);

	imgThresh2 = GetThresholdedImage(imgHSV2, 24, 0, 224, 46, 89, 256);

  
	   cvReleaseImage(&imgHSV2);
	   delete(imgHSV2);

 		cvSmooth(imgThresh2, imgThresh2, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel

		player200 = trackObject(imgThresh2, 0, 255, 0, 2);

/*
		//player 1 movement
		
		if( player100 == 1 ) {
			
			player1.move(0, -10);}

		else if(player100==-1){
			player1.move(0, 10);
		}
		//MOVIMIENTO GOLPE PLAYER1
	
		if (player1.getPosition().x <= 10){
		if(player100==2){
			
			player1.move(10, 0);
			
			
		}}

		//player 2 movement

		if(player200==1)
			player2.move(0, -10);
		else if(player200==-1)
			player2.move(0, 10);
		
		//MOVIMIENTO GOLPE PLAYER2
			
		if (player2.getPosition().x >= RENDERWIDTH-player2.getSize().x-10){
			  
		if(player200==-2){
			
			player2.move(-10, 0);
			
			
		}}

		//player 1 and wall collision
		if(player1.getPosition().y <= 0)
			player1.setPosition(0, 0);
		if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y)
			player1.setPosition(0, RENDERHEIGHT - player1.getSize().y);

		//PLAYER1 AND WALL BACK COLLISION
		if(player1.getPosition().x != 0)
			player1.move(-1,0);
		
		//PLAYER2 AND WALL BACK COLLISION
		if(player2.getPosition().x != RENDERWIDTH-player2.getSize().x)
			player2.move(1,0);
		
		//player 2 and wall collision
		if(player2.getPosition().y <= 0)
			player2.setPosition(RENDERWIDTH - player2.getSize().x, 0);
		if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y)
			player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y);

		//ball and wall collision
		if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter)
		{
			ballVelY *= -1;
			bounce.play();
		}

		//ball and player 1 collision
		if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x)
		{
			if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y) || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y && ball.getPosition().y >= player1.getPosition().y){


	if (player1.getPosition().x > 14){

				ballVelX = (ballVelX - 2) * -1;
				ball.setFillColor(sf::Color(255,0,0));
				perfecthit.play();
		
			}

	else if (player1.getPosition().x <= 14){

				ballVelX = (ballVelX - 1) * -1;
				ball.setFillColor(sf::Color(0,0,255));
				bounce.play();
}
			

			}

			else
			{
 				ball.setFillColor(sf::Color(255,255,255));
				point.play();
				player2Score += 1;  
				ballX = RENDERWIDTH / 2 - ball.getRadius();
				if (BALLSPEED < 8){
					BALLSPEED += 0.2;
					}
				ballVelX = BALLSPEED;
				score2.setString(convertInt(player2Score));
				score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);

				if (p2Len > 40)
					p2Len -= 10;
				player2.setSize(sf::Vector2f(15, p2Len));
				if (p1Len < 100)
					p1Len += 10;
				player1.setSize(sf::Vector2f(15, p1Len));
				
			}
		}//fin IF

		//ball and player 2 collision
if (ball.getPosition().x + ballDiameter >= player2.getPosition().x)
		{

			if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y) || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y && ball.getPosition().y >= player2.getPosition().y)
			{


				if (player2.getPosition().x < (RENDERWIDTH-9-player2.getSize().x)){

				ballVelX = (ballVelX + 2) * -1;
				ball.setFillColor(sf::Color(255,0,0));
				perfecthit.play();
				
			
					}

				else if (player2.getPosition().x >= (RENDERWIDTH-9-player2.getSize().x)){

				ballVelX = (ballVelX + 1) * -1;
				ball.setFillColor(sf::Color(0,255,0));
				bounce.play();

					}//fin if elseh
			}
				
			
			else
			{

				ball.setFillColor(sf::Color(255,255,255));
				point.play();
				player1Score += 1;
				ballX = RENDERWIDTH / 2 - ball.getRadius();
				if (BALLSPEED < 8)
					BALLSPEED += 0.5;
				ballVelX = -BALLSPEED;
				score1.setString(convertInt(player1Score));
				if (p1Len > 40)
					p1Len -= 10;
				player1.setSize(sf::Vector2f(15, p1Len));
				
				if (p2Len < 10)
					p2Len += 10;
				player2.setSize(sf::Vector2f(15, p2Len));
			}//fin else
		}//fin IF
*/
		//ball position update
		ballX += ballVelX;
		ballY += ballVelY;
		ball.setPosition(ballX, ballY);

		//render updates
		pong.clear();
		pong.draw(score1);
		pong.draw(score2);
		pong.draw(player1);
		pong.draw(player2);
		pong.draw(ball);
		pong.display();

	 
		
	}//fin for

	   cvReleaseCapture(&capture); 
           cvReleaseImage(&imgThresh);
	   cvReleaseImage(&imgThresh2);             
           cvReleaseImage(&frame);   
	   
      	   cvReleaseImage(&imgTracking);


//cvReleaseImage(&imgTemp); revisar este puntero

	   delete(moments);

	return 0;
}