int main()
{
   image source;
   grayimage idest;

   source = get_ppm(stdin);
   idest = tograyscale(source);
   free_img(source);
   source = tocolor(idest);
   output_ppm(stdout, source);
   free_img(source); free_img((image)idest);
   return 0;
}
image get_ppm(FILE *pf)
{
        char buf[PPMREADBUFLEN], *t;
        image img;
        unsigned int w, h, d;
        int r;

        if (pf == NULL) return NULL;
        t = fgets(buf, PPMREADBUFLEN, pf);
        /* the code fails if the white space following "P6" is not '\n' */
        if ( (t == NULL) || ( strncmp(buf, "P6\n", 3) != 0 ) ) return NULL;
        do
        { /* Px formats can have # comments after first line */
           t = fgets(buf, PPMREADBUFLEN, pf);
           if ( t == NULL ) return NULL;
        } while ( strncmp(buf, "#", 1) == 0 );
        r = sscanf(buf, "%u %u", &w, &h);
        if ( r < 2 ) return NULL;

        r = fscanf(pf, "%u", &d);
        if ( (r < 1) || ( d != 255 ) ) return NULL;
        fseek(pf, 1, SEEK_CUR); /* skip one byte, should be whitespace */

        img = alloc_img(w, h);
        if ( img != NULL )
        {
            size_t rd = fread(img->buf, sizeof(pixel), w*h, pf);
            if ( rd < w*h )
            {
               free_img(img);
               return NULL;
            }
            return img;
        }
}
Ejemplo n.º 3
0
static void gdal_nif_img_resource_cleanup(ErlNifEnv* env, void* arg)
{
    /* Delete any dynamically allocated memory stored in gdal_img_handle */
    DEBUG("FrEE img\r\n");
    gdal_img_handle* handle = (gdal_img_handle*)arg;
    free_img(handle);
}
Ejemplo n.º 4
0
image read_ppm(char* fis_in)
{
    image img;
    unsigned int w, h;
    char a;
    int b;

    FILE *f = fopen(fis_in, "r");
    if (f == NULL) {
        perror("Error opening input file");
        return NULL;
    }

    fscanf(f, "%c%d\n", &a, &b);
    fscanf(f, "%u %u\n", &w, &h);
    fscanf(f, "%d\n", &b);

    fpos_t curr_pos;
    fgetpos(f, &curr_pos);
    fseek (f , SEEK_CUR, SEEK_END);
    long f_size = ftell (f);
    fsetpos(f, &curr_pos);


    char* buf = malloc(f_size * sizeof(char));

    img = alloc_img(w, h);
    if (img != NULL) {
        size_t rd = fread(buf, 1, f_size, f);
        if (rd < w * h) {
            free_img(img);
            fclose(f);
            return NULL;
        }
        char *tok = strtok(buf, "\n");
        unsigned int i = 0, j = 0;
        while (tok != NULL)
        {
            if (j == 3) {
                j = 0;
                i++;
            }
            if (j % 3 == 0)
                img->buf[i].r = atoi(tok);
            else if (j % 3 == 1)
                img->buf[i].g = atoi(tok);
            else
                img->buf[i].b = atoi(tok);
            tok = strtok(NULL, "\n");
            j++;
            
        }
        free(buf);
        fclose(f);
        return img;
    }
    fclose(f);
    return img;
}
Ejemplo n.º 5
0
image
read_ppm (FILE * pf)
{
  char buf[PPMREADBUFLEN], *t;
  image img;
  unsigned int w, h, d;
  int r;

  if (pf == NULL)
    return NULL;
  t = fgets (buf, PPMREADBUFLEN, pf);
  if ((t == NULL) || (strncmp (buf, "P5\n", 3) != 0))
    return NULL;
  do
    {				/* Px formats can have # comments after first line */
      t = fgets (buf, PPMREADBUFLEN, pf);
      if (t == NULL)
	return NULL;
    }
  while (strncmp (buf, "#", 1) == 0);
  r = sscanf (buf, "%u %u", &w, &h);
  if (r < 2)
    return NULL;
  // The program fails if the first byte of the image is equal to 32. because
  // the fscanf eats the space and the image is read with some bit less
  r = fscanf (pf, "%u\n", &d);
  if ((r < 1) || (d != 255))
    return NULL;
  img = alloc_img (w, h);
  if (img != NULL)
    {
      size_t rd = fread (img->buf, sizeof (pixel_t), w * h, pf);
      if (rd < w * h)
	{
	  free_img (img);
	  return NULL;
	}
      return img;
    }
}
Ejemplo n.º 6
0
int main (int argc, char **argv) 
{
  FILE *fp;
  struct TIFF_img input_img, green_img, color_img;
  double **img1,**img2;
  int32_t i,j,pixel;

  if ( argc != 2 ) error( argv[0] );

  /* open image file */
  if ( ( fp = fopen ( argv[1], "rb" ) ) == NULL ) {
    fprintf ( stderr, "cannot open file %s\n", argv[1] );
    exit ( 1 );
  }

  /* read image */
  if ( read_TIFF ( fp, &input_img ) ) {
    fprintf ( stderr, "error reading file %s\n", argv[1] );
    exit ( 1 );
  }

  /* close image file */
  fclose ( fp );

  /* check the type of image data */
  if ( input_img.TIFF_type != 'c' ) {
    fprintf ( stderr, "error:  image must be 24-bit color\n" );
    exit ( 1 );
  }

  /* Allocate image of double precision floats */
  img1 = (double **)get_img(input_img.width,input_img.height,sizeof(double));
  img2 = (double **)get_img(input_img.width,input_img.height,sizeof(double));

  /* copy green component to double array */
  for ( i = 0; i < input_img.height; i++ )
  for ( j = 0; j < input_img.width; j++ ) {
    img1[i][j] = input_img.color[1][i][j];
  }

  /* Filter image along horizontal direction */
  for ( i = 0; i < input_img.height; i++ )
  for ( j = 1; j < input_img.width-1; j++ ) {
    img2[i][j] = (img1[i][j-1] + img1[i][j] + img1[i][j+1])/3.0;
  }

  /* Fill in boundary pixels */
  for ( i = 0; i < input_img.height; i++ ) {
    img2[i][0] = 0;
    img2[i][input_img.width-1] = 0;
  }

  /* Set seed for random noise generator */
  srandom2(1);

  /* Add noise to image */
  for ( i = 0; i < input_img.height; i++ )
	  for ( j = 1; j < input_img.width-1; j++ ) {
    img2[i][j] += 32*normal();
  }

  /* set up structure for output achromatic image */
  /* to allocate a full color image use type 'c' */
  get_TIFF ( &green_img, input_img.height, input_img.width, 'g' );
    
  /* set up structure for output color image */
  /* Note that the type is 'c' rather than 'g' */
  get_TIFF ( &color_img, input_img.height, input_img.width, 'c' );

  /* copy green component to new images */
  for ( i = 0; i < input_img.height; i++ )
  for ( j = 0; j < input_img.width; j++ ) {
    pixel = (int32_t)img2[i][j];
    if(pixel>255) {
      green_img.mono[i][j] = 255;
    }
    else {
      if(pixel<0) green_img.mono[i][j] = 0;
      else green_img.mono[i][j] = pixel;
    }
  }

  /* Illustration: constructing a sample color image -- interchanging the red and green components from the input color image */
  for ( i = 0; i < input_img.height; i++ )
      for ( j = 0; j < input_img.width; j++ ) {
          color_img.color[0][i][j] = input_img.color[1][i][j];
          color_img.color[1][i][j] = input_img.color[0][i][j];
          color_img.color[2][i][j] = input_img.color[2][i][j];
      }

  /* open green image file */
  if ( ( fp = fopen ( "green.tif", "wb" ) ) == NULL ) {
    fprintf ( stderr, "cannot open file green.tif\n");
    exit ( 1 );
  }

  /* write green image */
  if ( write_TIFF ( fp, &green_img ) ) {
    fprintf ( stderr, "error writing TIFF file %s\n", argv[2] );
    exit ( 1 );
  }

  /* close green image file */
  fclose ( fp );
    
    
  /* open color image file */
  if ( ( fp = fopen ( "color.tif", "wb" ) ) == NULL ) {
      fprintf ( stderr, "cannot open file color.tif\n");
      exit ( 1 );
  }
    
  /* write color image */
  if ( write_TIFF ( fp, &color_img ) ) {
      fprintf ( stderr, "error writing TIFF file %s\n", argv[2] );
      exit ( 1 );
  }
    
  /* close color image file */
  fclose ( fp );

  /* de-allocate space which was used for the images */
  free_TIFF ( &(input_img) );
  free_TIFF ( &(green_img) );
  free_TIFF ( &(color_img) );
  
  free_img( (void**)img1 );
  free_img( (void**)img2 );  

  return(0);
}
Ejemplo n.º 7
0
static void destroy_img_handle(gdal_img_handle* handle) {
    free_img(handle);
    enif_release_resource(handle);
}
Ejemplo n.º 8
0
// Libere l'image source et l'image de destination
void free_all_img(img_t* img, img_t* img2){
  free_img(img); //libère l'image source
  free_img(img2); //libère l'image destination
}
Ejemplo n.º 9
0
int main(int argc, char **argv)
{
	init_spus();
	srand((unsigned)time(NULL));
	char *fis_in, *fis_out;
	int zoom, rows, cols, i, j,
	overlap_spu, overlap_ppu,
	patch_w, patch_h, nr_patches;	

	if (argc < 8) {
		fprintf(stderr, "Error: Missing some parameters.\n");
		fprintf(stderr, "Run: ./program fis_in fis_out zoom nr_bucati_dim1 nr_bucati_dim2 banda_de_suprapunere_dim1 banda_de_suprapunere_dim2\n");
		return -1;
	}

	fis_in  = argv[1];
	fis_out = argv[2];
	zoom    = atoi(argv[3]);
	rows = atoi(argv[4]);
	cols = atoi(argv[5]);
	overlap_spu = atoi(argv[6]);
	overlap_ppu = atoi(argv[7]);

	
	image img_src = read_ppm(fis_in);
	if (img_src == NULL) {
		fprintf(stderr, "Error reading image file.\n");
		return -1;
	}

	patch_w = (zoom * img_src->width)  / cols;
	patch_h = (zoom * img_src->height) / rows;
	nr_patches = rows * cols;
	printf("PPU: NR PATCHES NECESARY = %d\n", nr_patches);

	int **spu_patch_id_vector = alloc_patch_id_vector(rows);
	if (spu_patch_id_vector == NULL)
		return -1;

	printf("PPU: ZOOM=%d ROWS=%d COLS=%d img->width=%d img->height=%d patch_w=%d patch_h=%d\n", zoom, rows, cols, img_src->width, img_src->height, patch_w, patch_h);

	int* rand_seed = make_seed_vector();
	if (rand_seed == NULL)
		return -1;
	int ***min_borders = malloc_align(SPU_THREADS * sizeof(int**), 4);
	if (min_borders == NULL) {
		perror("PPU: malloc_align failed in main");
		return -1;
	}
	for (i = 0; i < SPU_THREADS; i++) {
		min_borders[i] = alloc_aligned_matrix((rows-1), overlap_spu);
		if (min_borders[i] == NULL)
			return -1;
	}

	pixel_t **patches_to_send = make_patches(img_src, patch_w, patch_h, nr_patches);

	send_patch_info(&patch_w, &patch_h, &rows, &nr_patches, spu_patch_id_vector, patches_to_send, rand_seed, &overlap_spu, min_borders);

	stop_spus();

	int out_img_width = zoom * img_src->width;
	int out_img_height = zoom * img_src->height;
	image img_dst = alloc_img(out_img_width, out_img_height);

	for (i = 0; i < SPU_THREADS; i++) {
		printf("PPU: spu[%d]: ID= ", i);
		for (j = 0; j < rows; j++)
			printf("%d ", spu_patch_id_vector[i][j]);
		printf("\n");
	}

	make_final_image(img_dst, patch_w, patch_h, spu_patch_id_vector, rows, patches_to_send);
	write_ppm(fis_out, img_dst);

	free_img(img_src);
	free_img(img_dst);
	free_seed_vector(rand_seed);
	free_patch_id_vector(spu_patch_id_vector);
	for (i = 0; i < SPU_THREADS; i++)
		free_aligned_matrix(min_borders[i], rows-1);
	return 0;
}
Ejemplo n.º 10
0
/**
 Carga los ficheros de clasificacion automatica de estados y clases y clasifica las
 celulas de la imagen cuya ruta corresponde con la pasada por parametro.
 @param ruta, string de la ruta de la imagen a analizar.
 @param listCell, objeto ListadoCeulas que contiene todas las celulas de la imagen
 a analizar.
 */
void Clasificador::clasificarCelulas(string ruta, ListadoCelulas &listCell)
{	
	struct svm_model  *svmEst, *svmCl;
	
	float  media_est[N_ENTRADAS], desv_est[N_ENTRADAS];
	float  media_cl[N_ENTRADAS], desv_cl[N_ENTRADAS];
	int  y1, y2;
	int numCelulas, numPuntos;
	vector <int> *cx, *cy;
	Image *img, *img_grey, *img_bin;
	
	img = read_img ( ruta.c_str() );
	img_grey = rgb_to_gray (img);
	
	numCelulas = listCell.getNumCelulas();

	//Obtenemos path de los ficheros de clasificacion
	const char  *f_svm_Est = fichClasificEst.c_str();
	const char  *f_med_desv_Est = fichMediaDesviaEst.c_str();
	const char  *f_svm_Cl = fichClasificCl.c_str();
	const char  *f_med_desv_Cl = fichMediaDesviaCl.c_str();

	//Creamos los svm
	svmEst = crea_svm(f_svm_Est, f_med_desv_Est, media_est, desv_est);
	svmCl = crea_svm(f_svm_Cl, f_med_desv_Cl, media_cl, desv_cl);
	
	for(int i = 0; i < numCelulas; i++) 
	{
		PointList *puntos;

		if(listCell.getCelula(i)->getEstadoCelula() != "outimage" && 
		   listCell.getCelula(i)->getClaseCelula() != "outimage")
		{
			cx = listCell.getCelula(i)->getBordeCellX();
			cy = listCell.getCelula(i)->getBordeCellY();

			numPuntos = cx->size();
			puntos = alloc_point_list(numPuntos);
		
			//Convertimos puntos
			for(int j = 0; j < numPuntos; j++)
			{
				puntos->point[j] = alloc_point((*cy)[j], (*cx)[j]);
			}
			puntos->type = GEN_VALID;
		
			img_bin=computeBinImage ( puntos, get_num_rows ( img_grey ) , get_num_cols (img_grey));
		
			//  double* resul = texture_features_haralick(img, puntos, 1, 1);
			double * resul = texture_features_glrls_grey ( img_grey, img_bin, puntos, 1000, 0);
			float resul2[N_ENTRADAS], resul3[N_ENTRADAS];
		
			for(unsigned int z = 0; z < N_ENTRADAS; z++)
			{
				resul2[z] = (float)resul[z];
				resul3[z] = (float)resul[z];
			}

			//Salida clasificador clases
			y1 = saida_svm(svmCl, resul2, media_cl, desv_cl);

			switch(y1)
			{
				case 0:
					listCell.getCelula(i)->setClaseCelula("cn");
					break;
				case 1:
					listCell.getCelula(i)->setClaseCelula("sn");
					break;
			}
		
			//Salida clasificador estados
			y2 = saida_svm(svmEst, resul3, media_est, desv_est);

			switch (y2)
			{
				case 0:
					listCell.getCelula(i)->setEstadoCelula("ac");
					break;
				case 1:
					listCell.getCelula(i)->setEstadoCelula("hid");
					break;
				case 2:
					listCell.getCelula(i)->setEstadoCelula("vit");// vitelinas o atresicas
					break;
			}
		    free_point_list ( puntos );
		    free ( puntos->point );
		    free ( puntos );
		//	delete puntos;    
	
			free ( resul );
		}
	}
	destrue_svm(svmCl);
	destrue_svm(svmEst);
	
	free_img ( img );
	free ( img );
	free_img ( img_grey );
	free ( img_grey );
}
Ejemplo n.º 11
0
/**
 Realiza la deteccion de todas las celulas de la imagen de forma automatica.
 */
bool DeteccionAut::deteccionBordesNoSupervisado()
{
    // Maximun number of objects in the image
    int NUM_CELLS (10000 );
    // Maximun roundness of interested objects in the image for unsupervised algorithm
    double  MAX_ROUND 	( 1.4 );
    int i, l;
    int nout;
    PointList **out;

    if(diamMax != 0)
    {
        MAX_DIAMETER = diamMax / calibracion;
    }
    else
    {
        MAX_DIAMETER = MAX_DIAMETER / calibracion;
    }

    if(diamMin != 0)
    {
        MIN_DIAMETER = diamMin / calibracion;
    }
    else
    {
        MIN_DIAMETER = MIN_DIAMETER / calibracion;
    }

    // Read the input image
    img = read_img ( ruta.c_str() );
    if ( !is_rgb_img ( img ) || (img == NULL))
    {
        fprintf ( stderr, "Input image ( %s ) must be color image !", ruta.c_str() );
        return false;
    }

    /********************************Reloj**************************************/
    // comienzo = clock();
    /***************************************************************************/

    /***************************************************************************/
    string mensaje, titulo;

    //mensaje = "Se va a proceder al cálculo de los bordes de los ovocitos, el proceso durara aproximadamente 1 minuto durante el cual la aplicación quedara bloqueada, ¿Esta seguro de continuar?";
    mensaje = "The automatic oocyte edge detection is going to be performed. The application will be unaccesible during this process. Are you sure that you want to continue?";

    //titulo = "Cálculo automatico de bordes de los ovocitos";
    titulo = "Oocyte edge detection";

    if(Dialogos::dialogoConfirmacion(mensaje, titulo))
    {
        //DialogoBarraProgres dProgres("Detectando Bordes");
        DialogoBarraProgres dProgres("Oocyte edge detection");
        dProgres.ejectuaDialogoProgreso();
        dProgres.setEstadoBarraProgreso(0.1);
        dProgres.setPercentText(0.1);
        Utiles::actualizarInterfaz();
        /***************************************************************************/
        // Detect the edges in the input image
        num_rows=get_num_rows(img);
        num_cols=get_num_cols(img);

        /*Este dobre bucle que ven a continuacion e a aplicacion do filtro de Canny para distintos umbrais
        e suavizados (distintas escalas). O que obtemos e en contour (unha estrutura da libreria fourier.0.8
        que almacena os bordes que teñen mais de MIN_LENGTH pixels) e en n_all o numero de borde. */
        // Este paso e independente de que o algoritmo se aplique de forma supervisada ou non supervisada.
        //num_edges = 0;

        if(num_rows > MAX_ROWS_IMAGE || num_cols > MAX_COLS_IMAGE) {
            fprintf(stderr, "Error: image of size %i x %i too large (max. size= %i x %i): border detection aborted\n", num_rows, num_cols, MAX_ROWS_IMAGE, MAX_COLS_IMAGE);
            Dialogos::dialogoError("Image too large for border detection", "Error");
            return false;
        }

        img_grey=rgb_to_gray(img);
        // Aplicando o filtro de canny multiescalar
        contour=detect_edge_multiscalar_canny ( img_grey,  &num_edges, MIN_DIAMETER, NUM_CELLS);
        if ( IS_NULL( contour)) {
            printf ( "Invalid point list objects !");
        }
        //	printf("Tempo transcurrido: %f bordes= %d \n", stop_timer ( start_time), num_edges) ;

        /**********************************fase 1****************************/
        /* final = clock();
        cout<<"Tiempo fase 1 "<<(final - comienzo)/(double) CLOCKS_PER_SEC<<endl;
        comienzo = clock();*/

        dProgres.setEstadoBarraProgreso(0.5);
        dProgres.setPercentText(0.5);
        Utiles::actualizarInterfaz();
        /**************************************************************************/
        // A partir de aqui fanse calculos para analizar os bordes que hai en contour e asi mostrar so os que cremos que son bordes de govocitos maduros.

        //utilizando funcion aplico a deteccion non supervisada
        out=nonSuperviseDetection(contour, num_edges, num_cols, num_rows, MIN_DIAMETER, MAX_DIAMETER, MAX_ROUND, &nout);

        /**********************************Reloj fase 2****************************/
        /* final = clock();
        cout<<"Tiempo fase 2 "<<(final - comienzo)/(double) CLOCKS_PER_SEC<<endl;
        comienzo = clock();*/

        dProgres.setEstadoBarraProgreso(0.9);
        dProgres.setPercentText(0.9);
        Utiles::actualizarInterfaz();
        /**************************************************************************/

        for ( l = 0; l <nout; l++)
        {
            /************************Pintado govocitos*************************/
            PointList *p = out[l];

            /*Guardamos los puntos en un objeto celula y lo añadimos al objeto de
            listado de celulas*/
            pasoCoordSistemaGovocitos(p);
            /*******************************************************************/
        }

        for(i=0; i<nout; i++)
        {
            free_point_list(out[i]);
            free(out[i]->point);
            free(out[i]);
        }
        free(out);
        free_img(img);
        free_img(img_grey);
        free(img);
        free(img_grey);

        /**********************************Reloj fase 3****************************/
        /* final = clock();
        cout<<"Tiempo fase 3 "<<(final - comienzo)/(double) CLOCKS_PER_SEC<<endl;*/

        dProgres.setEstadoBarraProgreso(1);
        dProgres.setPercentText(1);
        Utiles::actualizarInterfaz();
        dProgres.cierraVentanaProgreso();
        /**************************************************************************/
    }
    else
    {
        return false;
    }

    return true;
}
Ejemplo n.º 12
0
void main(int argc, char *argv[]) {
  char outname[512], inname[512], *boh;
  int len, i, j, total;
  IMAGE *img = NIL, *newimg = 0;
  struct cmap_color *cmap;
  struct gl_color *gl_buffer;

  toonz_init(DUMMY_KEY_SLOT, (int *)&argc, argv);
  InibisciDongle();
  unprotect_lib();

  if (argc < 2) {
    printf("### %s error: missing argument\n", argv[0]);
    printf(" usage: %s infile \n", argv[0]);
    exit(0);
  }

  if (*argv[1] == '-') {
    printf("bad filename <%s> \n", argv[1]);
    exit(0);
  }

  printf("\n\n");

  for (i = 1; i < argc; i++) {
    strcpy(inname, argv[i]);

    len = strlen(inname);
    if (len < 4 || (STR_NE(inname + len - 4, ".tzu") &&
                    STR_NE(inname + len - 4, ".tzp"))) {
      printf("### %s error: file %s is not tz(up)\n", argv[0], inname);
      continue;
    }

    /*   printf(">> Loading %s\n", inname); */

    img = img_read_tzup_info(inname);
    if (!img) {
      printf("### %s error: file %s not found\n", argv[0], inname);
      continue;
    }

    printf(" > IMAGE: %s \n\n", inname);
    printf("   > Dimension:    xsize=%d\t\tysize=%d\n", img->pixmap.xsize,
           img->pixmap.ysize);
    printf("   > Savebox:\n");
    printf("   >   Start       x0=%d\t\ty0=%d \n", img->pixmap.xD,
           img->pixmap.yD);
    printf("   >   Dimensions  xsize=%d\t\tysize=%d \n", img->pixmap.xSBsize,
           img->pixmap.ySBsize);
    printf("   > Resolution:   x_dpi=%g\ty_dpi=%g \n", img->pixmap.x_dpi,
           img->pixmap.y_dpi);
    printf("   > H-position (pixels): %g \n", img->pixmap.h_pos);

    printf("\n");
    if (img->history) print_history(img->history);

    printf("\n\n");
    free_img(img);
    img = NIL;
  }

  printf(" Bye!!\n");
}