コード例 #1
0
ファイル: cube2d.cpp プロジェクト: yslib/cube
void Cube2d::paintEvent(QPaintEvent * event)
{
	const std::vector<sRGB> & rgbs = (((MainWindow *)parentWidget())->getCubePosition()).rgbs;
	//if (video != NULL)
	//	rgbs = video->getRGB();
	//for (int i = rgbs.size(); i < 9; i++)
	//	rgbs.push_back(sRGB(255, 255, 255));

	//textEdit->clear();
	QString colorVal;
	int colorTag;
	QColor color;
	int r, g, b;
	int h;
	double s, v;
	//char colorrgb[4];
	//colorrgb[3] = '\0';
	((MainWindow *)parentWidget())->setTextEditContent(tr(""));
    
	QTextStream in(file);
	for (int k = 0; k < 6; k++)
	{
		for (int i = 0; i < 3; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				r=rgbs[k * 9 + i * 3 + j].r;
				g=rgbs[k * 9 + i * 3 + j].g;
				b=rgbs[k * 9 + i * 3 + j].b;
				bgr2hsv(rgbs[k*9+i * 3 + j].b, rgbs[k * 9+i * 3 + j].g, rgbs[k * 9 + i * 3 + j].r, h, s, v);
				color = threshold(h, s, v, colorTag);
				//color = thresholdRGB(r,g,b,colorTag);
				faceColors[k * 9 + i * 3 + j] = colorTag;
				int leftTopX= FBLRUD->operator[](k).x();
				int leftTopY = FBLRUD->operator[](k).y();
				//colorrgb[0] = r; colorrgb[1] = g; colorrgb[2] = b;
				//QString colorVal(colorrgb);
				((MainWindow *)parentWidget())->sendData(colorVal);
				//in << tr("%1 %2 %3 %4 %5 %6\n").arg(rgbs[k * 9 + i * 3 + j].r).arg(rgbs[k * 9 + i * 3 + j].g).arg(rgbs[k * 9 + i * 3 + j].b).arg(h).arg(s).arg(v);
				//in << tr("%1%2%3").arg((char)r).arg((char)g).arg((char)b);
//                if(r != 0 && g!= 0 && b != 0)
//				colorVal += QString(tr("%1 %2 %3 1\r\n").arg((int)r).arg((int)g).arg((int)b));
				painter->begin(this);
				painter->setPen(color);
				painter->setBrush(color);
				painter->drawRect(QRectF(
					leftTopX+(j + 1)*margin + j*SquareLenth, 
					leftTopY+(i + 1)*margin + i*SquareLenth, 
					SquareLenth, 
					SquareLenth));
				painter->end();	
			}
		}
	}
    //in << colorVal;
}
コード例 #2
0
int main( int argc, char** argv )
{
  IplImage* hsv_img;
  IplImage** hsv_ref_imgs;
  IplImage* l32f, * l;
  histogram* ref_histo;
  double max;
  int i;

  arg_parse( argc, argv );

  /* compute HSV histogram over all reference image */
  hsv_img = bgr2hsv( in_img );
  hsv_ref_imgs = (IplImage**)malloc( num_ref_imgs * sizeof( IplImage* ) );
  for( i = 0; i < num_ref_imgs; i++ )
    hsv_ref_imgs[i] = bgr2hsv( ref_imgs[i] );
  ref_histo = calc_histogram( hsv_ref_imgs, num_ref_imgs );
  normalize_histogram( ref_histo );

  /* compute likelihood at every pixel in input image */
  fprintf( stderr, "Computing likelihood... " );
  fflush( stderr );
  l32f = likelihood_image( hsv_img, ref_imgs[0]->width,
			   ref_imgs[0]->height, ref_histo );
  fprintf( stderr, "done\n");

  /* convert likelihood image to uchar and display */
  cvMinMaxLoc( l32f, NULL, &max, NULL, NULL, NULL );
  l = cvCreateImage( cvGetSize( l32f ), IPL_DEPTH_8U, 1 );
  cvConvertScale( l32f, l, 255.0 / max, 0 );
  cvNamedWindow( "likelihood", 1 );
  cvShowImage( "likelihood", l );
  cvNamedWindow( "image", 1 );
  cvShowImage( "image", in_img );
  cvWaitKey(0);
}
コード例 #3
0
ファイル: cube2d.cpp プロジェクト: yslib/cube
void Cube2dThread::run()
{
	while (stopped == false)
	{
		QString colorVal;
		int colorTag;

		for (int k = 0; k < 6; k++)
		{
			for (int i = 0; i < 3; i++)
			{
				for (int j = 0; j < 3; j++)
				{
					int h;
					double s, v;
					bgr2hsv(rgbs[k * 9 + i * 3 + j].b, rgbs[k * 9 + i * 3 + j].g, rgbs[k * 9 + i * 3 + j].r, h, s, v);

					QColor color = threshold(h, s, v, colorTag);
					faceColors[k * 9 + i * 3 + j] = colorTag;
					int leftTopX = FBLRUD->operator[](k).x();
					int leftTopY = FBLRUD->operator[](k).y();

					//colorVal += QString(tr("%1 %2 %3\r\n").arg(h).arg(s).arg(v));

					if (cubeImage == NULL)
						qDebug() << "asdf";
					painter->begin(cubeImage);
					painter->setPen(color);
					painter->setBrush(color);
					painter->drawRect(QRectF(
						leftTopX + (j + 1)*margin + j*SquareLenth,
						leftTopY + (i + 1)*margin + i*SquareLenth,
						SquareLenth,
						SquareLenth));
					painter->end();
				}
			}
		}
		//((MainWindow *)parentWidget())->setTextEditContent(colorVal);
		cubeLabel->setPixmap(QPixmap::fromImage(*cubeImage));
	}
	stopped = false;
}
コード例 #4
0
ファイル: objectTracking.c プロジェクト: notooth/reconos
////////////////////////////////////////////////////////////////////////////
// MAIN ////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
///
/// Main program.
///
int main( int argc, char *argv[] )
{

    CvCapture *video;
    CvVideoWriter *writer;
    IplImage *frame;
    IplImage *hsv;
    char *win_name = "Source Frame";
    char key = 0;
    tcp_connection *con;
    int frame_count = 0, result;
    int i;
    max_frames = 5000;
    unsigned char *byte_stream;
 
    // register signal handler for SIGINT und SIGPIPE
    // the latter occurs if the server terminates the connection
    /*
    DEBUG_PRINT( DEBUG_NOTE, "registering signal" )
        if ( signal( SIGINT, sig_handler ) == SIG_ERR ||
             signal( SIGPIPE, sig_handler ) == SIG_ERR ) {
        fprintf( stderr, "failed to register signal handler.\n" );
        exit( 1 );
    }
    */
    parse_args( argc, argv );

    // open the capture source
    switch ( source ) {
    case SOURCE_FILE:
        video = cvCreateFileCapture( infilename );
        break;
    case SOURCE_CAM:
        video = cvCreateCameraCapture( camera );
        break;
    default:
        fprintf( stderr, "strange source\n" );
        exit( 1 );
    }

    if ( !video ) {
        fprintf( stderr, "unable to capture source\n" );
        exit( 1 );
    }
    // connect to remote host
    con = tcp_connection_create( host, port );
    if ( !con ) {
        fprintf( stderr, "unable to connect to %s, port %d\n", host,
                 port );
        exit( 1 );
    }
    printf( "Connected to %s, port %d.\n", host, port );

    frame = cvQueryFrame( video );
    if ( !frame ) {
        fprintf( stderr, "unable to capture video.\n" );
        exit( 1 );
    }
    number_of_frames++;

    if ( netimage_send_header( con, frame ) <= 0 ) {
        fprintf( stderr, "unable to send header information.\n" );
        exit( 1 );
    }

    printf
        ( "Sending image stream (%d x %d, depth %u, %d channels (size: %d bytes)).\n"
          "Press 'q' to abort.\n", frame->width, frame->height,
          frame->depth, frame->nChannels, frame->imageSize );

    // open capture file, if desired
    if ( output ) {

        strncat( outfilename, ".mpg", MAX_FILENAMELEN );

        writer =
            cvCreateVideoWriter( outfilename, atofourcc( fourcc ), fps,
                                 cvSize( frame->width, frame->height ),
                                 frame->nChannels > 1 ? 1 : 0 );
        if ( writer == NULL ) {
            fprintf( stderr, "unable to create output file '%s'\n",
                     outfilename );
/*             exit (1);*/
        } else
            printf( "Writing to output file '%s'.\n", outfilename );
    }

    // for fps measurement
    struct timeval current, last;
    unsigned int diff;	// time difference in usecs
    int x0 = 0, y0 = 0, width = 0, height = 0;
	
    gettimeofday(&last, NULL);
    
    // show first frame for region selection   
    //frame = cvQueryFrame( video );
    //cvNamedWindow( win_name, 1 );
    //cvShowImage( win_name, frame );
    //if (output)
    //   cvWriteFrame( writer, frame );

    // get input region   
    char* win_name2 = "First frame";
    params p;
    CvRect* r;
    int x1, y1, x2, y2;
    int region[4];

  /* use mouse callback to allow user to define object regions */
  /*p.win_name = win_name2;
  p.orig_img = cvClone( frame );
  p.cur_img = NULL;
  p.n = 0;

  cvNamedWindow( win_name2, 1 );
  cvShowImage( win_name2, frame );
  cvSetMouseCallback( win_name2, &mouse, &p );
  printf("\nSelect Object and press [ENTER] !\n");
  cvWaitKey( 0 );

  cvDestroyWindow( win_name2 );
  cvReleaseImage( &p.orig_img );
  if( p.cur_img )
      cvReleaseImage( &(p.cur_img) );*/

  /* extract regions defined by user; store as an array of rectangles */
  if( p.n > 0 ){
      p.loc1[0].x = 0;
      p.loc1[0].y = 0;
      p.loc2[0].x = 0;
      p.loc2[0].y = 0;

      r = malloc(  sizeof( CvRect ) );
      x1 = MIN( p.loc1[0].x, p.loc2[0].x );
      x2 = MAX( p.loc1[0].x, p.loc2[0].x );
      y1 = MIN( p.loc1[0].y, p.loc2[0].y );
      y2 = MAX( p.loc1[0].y, p.loc2[0].y );
      width = x2 - x1;
      height = y2 - y1;

      /* ensure odd width and height */
      width = ( width % 2 )? width : width+1;
      height = ( height % 2 )? height : height+1;
      r[0] = cvRect( x1, y1, width, height );
      x0 = x1 + width/2;
      y0 = y1 + height/2;

      region[0] = x0;
      region[1] = y0;
      region[2] = width;
      region[3] = height;
   }


    //printf("\nx = %d\ny = %d\nwidth = %d\nheight = %d\n\n\n", x0, y0, width, height);

    // 1) convert bgr frame to hsv frame
    hsv = cvCreateImage( cvGetSize(frame), IPL_DEPTH_8U, 3 );
    bgr2hsv(frame, hsv);  
    result = tcp_send( con, hsv->imageData, hsv->imageSize);
    int counter = 1;
    //result = tcp_send( con, frame->imageData, frame->imageSize );

    result = tcp_send( con, (char *) region, 4 * sizeof(int));

    // confirm input with enter
    //printf("\nPress [ENTER]\n");
    //cvWaitKey( 0 );

    // TODO: send first frame + region data 
    //result = tcp_send( con, frame->imageData, frame->imageSize);
  
    number_of_particles = 100;

    // create particles data array
    particles_data = (particle_data *) malloc ((number_of_particles+1) * sizeof(particle_data));

    // quiet mode: no video output
    if (quiet){

         cvDestroyWindow( win_name );
    }

    // 1) send other frames
    // get video data and send/store it
#ifdef STORE_VIDEO
    //while ( ( frame = cvQueryFrame( video ) ) && ( char ) key != 'q' && !quit && number_of_frames <= 221 ) {
    while ( ( frame = cvQueryFrame( video ) ) && ( char ) key != 'q' && counter < max_frames) {
#else
    while ( ( frame = cvQueryFrame( video ) ) && ( char ) key != 'q' && counter < max_frames) {
#endif
        
        // 1) convert bgr frame to hsv frame
        bgr2hsv(frame, hsv); 
        result = tcp_send( con, hsv->imageData, hsv->imageSize );
        //fprintf(stderr, "\n///////////////////      number of frames %d     //////////////////////////////////////", number_of_frames);
        counter ++;
        //result = tcp_send( con, frame->imageData, frame->imageSize );

        if ( result > 0 ) {
            if ( !quiet ) {
                cvNamedWindow( win_name, 1 );

#ifdef NO_VGA_FRAMEBUFFER
#ifndef STORE_VIDEO          
	  if (number_of_frames > 2){
#else
 	  if (number_of_frames > 2 && number_of_frames % MAX_FRAMES == 0){
#endif
            // receive tcp package with particle data and display them in video
            // 1) receive tcp package with particles data
            //printf("\nreceive particles...");
            result = tcp_receive( con, (unsigned char*)particles_data, ((number_of_particles+1) * sizeof(particle_data)));
 
            if ( result > 0 ) {

               // 2) draw particles data         
               for (i=0; i<number_of_particles+1; i++){
         
	         // set OpenCV location points for bounding boxes
	         loc1.x = ntohl(particles_data[i].x1);
                 loc1.y = ntohl(particles_data[i].y1);
                 loc2.x = ntohl(particles_data[i].x2);
                 loc2.y = ntohl(particles_data[i].y2);
                 particles_data[i].best_particle = ntohl(particles_data[i].best_particle);

                 if (particles_data[i].best_particle > 0 ) particles_data[i].best_particle = TRUE;
                 
                 if (loc1.x <640 && loc2.x < 640 && loc1.y < 480 && loc2.y < 480)
                   // draw bounding box (red for best particle, blue else)
                   if (particles_data[i].best_particle == FALSE){
                 
                     cvRectangle( frame, loc1, loc2, CV_RGB(0,0,255), 1, 8, 0 ); 
                    } else {
                 
                      cvRectangle( frame, loc1, loc2, CV_RGB(255,0,0), 1, 8, 0 );   
                   }
	       }
             }
	   }        
#endif
                if (!quiet){
                  cvShowImage( win_name, frame );
                  //export_frame( frame, number_of_frames);
                  key = cvWaitKey( 2 );
                }
            }
            if ( output )
                cvWriteFrame( writer, frame );
        } else {
            printf( "connection lost.\n" );
            break;
        }
        //gettimeofday(&current, NULL);
        //diff = (current.tv_sec - last.tv_sec) * 1000000;
        //diff += (current.tv_usec - last.tv_usec);
	
        //fprintf(stderr, "FPS: %.2f\r", 1000000.0 / diff);
	
        //last.tv_sec = current.tv_sec;
        //last.tv_usec = current.tv_usec;
        number_of_frames++;
    }


/*
#ifdef STORE_VIDEO   
    cvReleaseCapture( &video );

    // 2) receive particle data and display particle data as Bounding Boxes
    switch ( source ) {
    case SOURCE_FILE:
        video = cvCreateFileCapture( infilename );
        break;
    case SOURCE_CAM:
        fprintf( stderr, "This part is only possible if video is stored into a file\n" );
        exit( 1 );
    default:
        fprintf( stderr, "strange source\n" );
        exit( 1 );
    }


    particles_data = malloc ((number_of_particles+1) * sizeof(particle_data));

    // get frames
    while ( ( frame = cvQueryFrame( video ) ) && ( char ) key != 'q' && !quit && number_of_frames <= 221 ) {


         // 1) receive tcp package with particles data
         // TODO
         result = tcp_receive( con, (char *)particles_data, ((number_of_particles+1) * sizeof(particle_data)));
 
         if ( result > 0 ) {

            // 2) draw particles data         
            for (i=0; i<number_of_particles+1; i++){
         
	         // set OpenCV location points for bounding boxes
	         loc1.x = particles_data[i].x1;
                 loc1.y = particles_data[i].y1;
                 loc2.x = particles_data[i].x2;
                 loc2.y = particles_data[i].y2;
                 
                 // draw bounding box (red for best particle, blue else)
                 if (particles_data[i].best_particle == TRUE){
                 
                    cvRectangle( frame, loc1, loc2, CV_RGB(255,0,0), 1, 8, 0 ); 
                 } else {
                 
                    cvRectangle( frame, loc1, loc2, CV_RGB(0,0,255), 1, 8, 0 );   
                 }
	    }
         }

         // display video frame
         if (!quiet){
              cvNamedWindow( win_name, 1 );
              cvShowImage( win_name, frame );
              key = cvWaitKey( 2 );
         }
         number_of_frames++;
    }
#endif
*/
    // clean up
    if (!quiet){

         cvDestroyWindow( win_name );
    }
    cvReleaseCapture( &video );
    if ( output )
        cvReleaseVideoWriter( &writer );
    tcp_connection_destroy( con );

    return 0;
}




/*
  Mouse callback function that allows user to specify the initial object
  regions.  Parameters are as specified in OpenCV documentation.
*/
void mouse( int event, int x, int y, int flags, void* param )
{
  params* p = (params*)param;
  CvPoint* loc;
  int n;
  IplImage* tmp;
  static int pressed = 0;
  
  /* on left button press, remember first corner of rectangle around object */
  if( event == CV_EVENT_LBUTTONDOWN )
    {
      n = p->n;
      if( n == 1 )
	return;
      loc = p->loc1;
      loc[n].x = x;
      loc[n].y = y;
      pressed = 1;
    }

  /* on left button up, finalize the rectangle and draw it in black */
  else if( event == CV_EVENT_LBUTTONUP )
    {
      n = p->n;
      if( n == 1 )
	return;
      loc = p->loc2;
      loc[n].x = x;
      loc[n].y = y;
      cvReleaseImage( &(p->cur_img) );
      p->cur_img = NULL;
      cvRectangle( p->orig_img, p->loc1[n], loc[n], CV_RGB(0,0,0), 1, 8, 0 );
      cvShowImage( p->win_name, p->orig_img );
      pressed = 0;
      p->n++;
    }

  /* on mouse move with left button down, draw rectangle as defined in white */
  else if( event == CV_EVENT_MOUSEMOVE  &&  flags & CV_EVENT_FLAG_LBUTTON )
    {
      n = p->n;
      if( n == 1 )
	return;
      tmp = cvClone( p->orig_img );
      loc = p->loc1;
      cvRectangle( tmp, loc[n], cvPoint(x, y), CV_RGB(255,255,255), 1, 8, 0 );
      cvShowImage( p->win_name, tmp );
      if( p->cur_img )
	cvReleaseImage( &(p->cur_img) );
      p->cur_img = tmp;
    }
}
コード例 #5
0
ファイル: trackerMP.cpp プロジェクト: rotty11/Tfm
/**
 * @brief Main principal
 * @param argc El número de argumentos del programa
 * @param argv Cadenas de argumentos del programa
 * @return Nada si es correcto o algún número negativo si es incorrecto
 */
int main( int argc, char** argv ) {
	
	if( argc < 5 )
		return -1;

	// Declaración de variables
	gsl_rng *rng;
	IplImage *frame, *hsv_frame;
	float **ref_histos, histo_aux[atoi(argv[4])][HTAM];
	CvCapture *video;
	particle **particles, **aux, **nuevas_particulas;
	CvScalar color_rojo = CV_RGB(255,0,0), color_azul = CV_RGB(0,0,255);
	float factor = 1.0 / 255.0, sum = 0.0f;
	CvRect *regions;
	int num_objects = 0;
	int MAX_OBJECTS = atoi(argv[3]), PARTICLES = atoi(argv[2]);
	FILE *datos;
	char name[45], num[3], *p1, *p2;
	double t_ini, t_fin;
	
	video = cvCaptureFromFile( argv[1] );
	if( !video ) {
		printf("No se pudo abrir el fichero de video %s\n", argv[1]);
		exit(-1);
	}

	int nFrames = (int) cvGetCaptureProperty( video , CV_CAP_PROP_FRAME_COUNT );
	first_frame = cvQueryFrame( video );
	num_objects = get_regions( &regions,  MAX_OBJECTS, argv[1] );
	if( num_objects == 0 )
		exit(-1);

	t_ini = omp_get_wtime();
	// Inicializamos el generador de números aleatorios
	gsl_rng_env_setup();
	rng = gsl_rng_alloc( gsl_rng_mt19937 );
	gsl_rng_set(rng, (unsigned long) time(NULL));

	hsv_frame = bgr2hsv( first_frame );
	nuevas_particulas = (particle**) malloc( num_objects * sizeof( particle* ) );
	for( int j = 0; j < num_objects; ++j )
		nuevas_particulas[j] = (particle*) malloc( PARTICLES * sizeof( particle ) );
	
	// Computamos los histogramas de referencia y distribuimos las partículas iniciales
	ref_histos = compute_ref_histos( hsv_frame, regions, num_objects );
	particles = init_distribution( regions, num_objects, PARTICLES );

	// Mostramos el tracking
	if( show_tracking ) {

		// Mostramos todas las partículas
		if( show_all )
			for( int k = 0; k < num_objects; ++k )
				for( int j = 0; j < PARTICLES; ++j )
					display_particle( first_frame, particles[k][j], color_azul );

		// Dibujamos la partícula más prometedora de cada objeto
		for( int k = 0; k < num_objects; ++k )
			display_particle( first_frame, particles[k][0], color_rojo );

		cvNamedWindow( "RGB", 1 );
		cvShowImage( "RGB", first_frame );
		cvWaitKey( 5 );
	}

	// Exportamos los histogramas de referencia y los frames
	if( exportar ) {
		export_ref_histos( ref_histos, num_objects );
		export_frame( first_frame, 1 );

		for( int k = 0; k < num_objects; ++k ) {
			sprintf( num, "%02d", k );
			strcpy( name, REGION_BASE);
			p1 = strrchr( argv[1], '/' );
			p2 = strrchr( argv[1], '.' );
			strncat( name, (++p1), p2-p1 );
			strcat( name, num );
			strcat( name, ".txt" );
			datos = fopen( name, "a+" );
			if( ! datos ) {
				printf("Error creando fichero para datos\n");
				exit(-1);;
			}
			fprintf( datos, "%d\t%f\t%f\n", 0, particles[k][0].x, particles[k][0].y );
			fclose( datos );
		}
	}

	// Bucle principal!!
	#pragma omp parallel num_threads(atoi(argv[4])) shared(sum)
	for(int i = 1; i < nFrames; ++i) {

		// Recordar que frame no se puede liberar debido al cvQueryFrame
		#pragma omp master
			frame = cvQueryFrame( video );
		#pragma omp barrier

		#pragma omp for schedule(guided,1)
		for( int f = 0 ; f < hsv_frame->height; ++f ) {
			float *ptrHSV = (float*) ( hsv_frame->imageData + hsv_frame->widthStep*f );
			unsigned char *ptrRGB = (unsigned char*) ( frame->imageData + frame->widthStep*f );
			float h;
			for( int col = 0, despH = 0; col < hsv_frame->width; ++col, despH+=3 ) {
				int despS = despH+1;
				int despV = despH+2;
				float b = ptrRGB[despH] * factor;
				float g = ptrRGB[despS] * factor;
				float r = ptrRGB[despV] * factor;
				float min = MIN(MIN(b, g), r);
				float max = MAX(MAX(b, g), r);
				ptrHSV[despV] = max; // v
				if( max != min ) {
					float delta = max - min;
					ptrHSV[despS] = delta / max; // s = (max - min) / max = 1.0 - (min / max)
					if( r == max )
						h = ( g - b ) / delta;
					else if( g == max )
						h = 2.0f + (( b - r ) / delta);
					else
						h = 4.0f + (( r - g ) / delta);
					h *= 60.0f;
					if(h < 0.0f)
						h += 360.0f;
					ptrHSV[despH] = h; // h
				}
				else {
					ptrHSV[despH] = 0.0f; // h
					ptrHSV[despS] = 0.0f; // s
				}
			}
		}

		// Realizamos la predicción y medición de probabilidad para cada partícula
		for( int k = 0; k < num_objects; ++k ) {

			sum = 0.0f;
			#pragma omp for reduction(+:sum) schedule(guided, 1)
			for( int j = 0; j < PARTICLES; ++j ) {
				transition( &particles[k][j], frame->width, frame->height, rng );
				particles[k][j].w = likelihood( hsv_frame, &particles[k][j], ref_histos[k], histo_aux[omp_get_thread_num()] );
				sum += particles[k][j].w;
			}
		
			// Normalizamos los pesos y remuestreamos un conjunto de partículas no ponderadas
			#pragma omp for
			for( int j = 0; j < PARTICLES; ++j )
				particles[k][j].w /= sum;
		}

		// Remuestreamos un conjunto de partículas no ponderadas
		#pragma omp for
		for (int k = 0; k < num_objects; ++k )
			resample( particles[k], PARTICLES, nuevas_particulas[k] );

		#pragma omp master
		{
			aux = particles;
			particles = nuevas_particulas;
			nuevas_particulas = aux;

			// Mostramos el tracking
			if( show_tracking ) {

				// Mostramos todas las partículas
				if( show_all )
					for( int k = 0; k < num_objects; ++k )
						for( int j = 0; j < PARTICLES; ++j )
							display_particle( frame, particles[k][j], color_azul );
	
				// Dibujamos la partícula más prometedora de cada objeto
				for( int k = 0; k < num_objects; ++k )
					display_particle( frame, particles[k][0], color_rojo );
				cvNamedWindow( "RGB", 1 );
				cvShowImage( "RGB", frame );
				cvWaitKey( 5 );
			}

			// Exportamos los histogramas de referencia y los frames
			if( exportar ) {
				export_frame( frame, i+1 );

				for( int k = 0; k < num_objects; ++k ) {
					sprintf( num, "%02d", k );
					strcpy( name, REGION_BASE);
					p1 = strrchr( argv[1], '/' );
					p2 = strrchr( argv[1], '.' );
					strncat( name, (++p1), p2-p1 );
					strcat( name, num );
					strcat( name, ".txt" );
					datos = fopen( name, "a+" );
					if( ! datos ) {
						printf("Error abriendo fichero para datos\n");
						exit(-1);
					}
					fprintf( datos, "%d\t%f\t%f\n", i, particles[k][0].x, particles[k][0].y );
					fclose( datos );
				}
			}
		}
	}
	
	// Liberamos todos los recursos usados (mallocs, gsl y frames)
	cvReleaseImage( &hsv_frame );
	cvReleaseCapture( &video );
	gsl_rng_free( rng );
	free( regions );

	for( int i = 0; i < num_objects; ++i ) {
		free( ref_histos[i] );
		free( particles[i] );
		free( nuevas_particulas[i] );
	}

	free( particles );
	free( nuevas_particulas );

	t_fin = omp_get_wtime();
	printf("%d\t%d\t%.10g\n", PARTICLES, num_objects, (t_fin - t_ini) * 1000);
}
コード例 #6
0
ファイル: trackerCopias.cpp プロジェクト: rotty11/Tfm
/**
 * @brief Main principal
 * @param argc El número de argumentos del programa
 * @param argv Cadenas de argumentos del programa
 * @return Nada si es correcto o algún número negativo si es incorrecto
 */
int main( int argc, char** argv ) {
	
	if( argc < 4 )
		return -1;

	// Declaración de variables
	gsl_rng *rng;
	IplImage *frame, *hsv_frame;
	histogram **ref_histos, *histo_aux;
	CvCapture *video;
	particle **particles, **aux, **nuevas_particulas;
	CvScalar color_rojo = CV_RGB(255,0,0), color_azul = CV_RGB(0,0,255);
	CvRect *regions;
	int num_objects = 0;
	int i = 1, MAX_OBJECTS = atoi(argv[3]), PARTICLES = atoi(argv[2]);
	FILE *datos;
	char name[45], num[3], *p1, *p2;
	clock_t t_ini, t_fin;
	double ms;
	
	video = cvCaptureFromFile( argv[1] );
	if( !video ) {
		printf("No se pudo abrir el fichero de video %s\n", argv[1]);
		exit(-1);
	}

	first_frame = cvQueryFrame( video );
	num_objects = get_regions( &regions,  MAX_OBJECTS, argv[1] );
	if( num_objects == 0 )
		exit(-1);

	t_ini = clock();
	hsv_frame = bgr2hsv( first_frame );
	histo_aux = (histogram*) malloc( sizeof(histogram) );
	histo_aux->n = NH*NS + NV;
	nuevas_particulas = (particle**) malloc( num_objects * sizeof( particle* ) );
	for( int j = 0; j < num_objects; ++j )
		nuevas_particulas[j] = (particle*) malloc( PARTICLES * sizeof( particle ) );
			
	// Computamos los histogramas de referencia y distribuimos las partículas iniciales
	ref_histos = compute_ref_histos( hsv_frame, regions, num_objects );
	particles = init_distribution( regions, num_objects, PARTICLES );

	// Mostramos el tracking
	if( show_tracking ) {

		// Mostramos todas las partículas
		if( show_all )
			for( int k = 0; k < num_objects; ++k )
				for( int j = 0; j < PARTICLES; ++j )
					display_particle( first_frame, particles[k][j], color_azul );

		// Dibujamos la partícula más prometedora de cada objeto
		for( int k = 0; k < num_objects; ++k )
			display_particle( first_frame, particles[k][0], color_rojo );

		cvNamedWindow( "Video", 1 );
		cvShowImage( "Video", first_frame );
		cvWaitKey( 5 );
	}

	// Exportamos los histogramas de referencia y los frames
	if( exportar ) {
		export_ref_histos( ref_histos, num_objects );
		export_frame( first_frame, 1 );

		for( int k = 0; k < num_objects; ++k ) {
			sprintf( num, "%02d", k );
			strcpy( name, REGION_BASE);
			p1 = strrchr( argv[1], '/' );
			p2 = strrchr( argv[1], '.' );
			strncat( name, (++p1), p2-p1 );
			strcat( name, num );
			strcat( name, ".txt" );
			datos = fopen( name, "a+" );
			if( ! datos ) {
				printf("Error creando fichero para datos\n");
				return -1;
			}
			fprintf( datos, "%d\t%f\t%f\n", 0, particles[k][0].x, particles[k][0].y );
			fclose( datos );
		}
	}

	cvReleaseImage( &hsv_frame );
	
	// Inicializamos el generador de números aleatorios
	gsl_rng_env_setup();
	rng = gsl_rng_alloc( gsl_rng_mt19937 );
	gsl_rng_set(rng, (unsigned long) time(NULL));

	// Recordar que frame no se puede liberar debido al cvQueryFrame
	while( frame = cvQueryFrame( video ) ) {
		hsv_frame = bgr2hsv( frame );

		// Realizamos la predicción y medición de probabilidad para cada partícula
		for( int k = 0; k < num_objects; ++k )
			for( int j = 0; j < PARTICLES; ++j ) {
				transition( &particles[k][j], frame->width, frame->height, rng );
				particles[k][j].w = likelihood( hsv_frame, &particles[k][j], ref_histos[k], histo_aux );
			}
			
		// Normalizamos los pesos y remuestreamos un conjunto de partículas no ponderadas
		normalize_weights( particles, num_objects, PARTICLES );
		for (int k = 0; k < num_objects; ++k )
			resample( particles[k], PARTICLES, nuevas_particulas[k] );
		aux = particles;
		particles = nuevas_particulas;
		nuevas_particulas = aux;

		// Mostramos el tracking
		if( show_tracking ) {

			// Mostramos todas las partículas
			if( show_all )
				for( int k = 0; k < num_objects; ++k )
					for( int j = 0; j < PARTICLES; ++j )
						display_particle( frame, particles[k][j], color_azul );
		
			// Dibujamos la partícula más prometedora de cada objeto
			for( int k = 0; k < num_objects; ++k )
				display_particle( frame, particles[k][0], color_rojo );
			cvNamedWindow( "Video", 1 );
			cvShowImage( "Video", frame );
			cvWaitKey( 5 );
		}

		// Exportamos los histogramas de referencia y los frames
		if( exportar ) {
			export_frame( frame, i+1 );

			for( int k = 0; k < num_objects; ++k ) {
				sprintf( num, "%02d", k );
				strcpy( name, REGION_BASE);
				p1 = strrchr( argv[1], '/' );
				p2 = strrchr( argv[1], '.' );
				strncat( name, (++p1), p2-p1 );
				strcat( name, num );
				strcat( name, ".txt" );
				datos = fopen( name, "a+" );
				if( ! datos ) {
					printf("Error abriendo fichero para datos\n");
					return -1;
				}
				fprintf( datos, "%d\t%f\t%f\n", i, particles[k][0].x, particles[k][0].y );
				fclose( datos );
			}
		}

		cvReleaseImage( &hsv_frame );
		++i;
	}
	
	// Liberamos todos los recursos usados (mallocs, gsl y frames)
	cvReleaseCapture( &video );
	gsl_rng_free( rng );
	free( histo_aux );
	free( regions );

	for( int i = 0; i < num_objects; ++i ) {
		free( ref_histos[i] );
		free( particles[i] );
		free( nuevas_particulas[i] );
	}

	free( particles );
	free( nuevas_particulas );

	t_fin = clock();
	ms = ((double)(t_fin - t_ini) / CLOCKS_PER_SEC) * 1000.0;
	printf("%d\t%d\t%.10g\n", PARTICLES, num_objects, ms);
}