Пример #1
0
int main(int argc, char** argv)
{
  const char *input_file  = argv[1];
  const char *output_file = argv[2];
  
  int num_generations = atoi(argv[3]);
  int population_size = atoi(argv[4]);  
  // population size, must be multiple of 4 right now
  assert(population_size % 4 == 0);
  
  // Load the desired image
  RGB *desired_image;  
  int width, height, max;
  desired_image = readPPM(input_file, &width, &height, &max);
  
  // Compute an image
  RGB *found_image = (RGB*)malloc(width*height*sizeof(RGB));
  compImage(desired_image, width, height, max, 
	    num_generations, population_size, found_image, output_file);
  
  // Write it back into an output file
  writePPM(output_file, width, height, max, found_image);
  
  free(found_image);
  free(desired_image);
  
  return(0);
}
Пример #2
0
/*
 * Read an image
 */
int RImage::read(char file[100]) {
	if (strstr(file, ".ppm") != NULL) {
		type = PPM;
		readPPM(file);

	} else if (strstr(file, ".pgm") != NULL){
		type = PGM;
		readPGM(file);

	} else if (strstr(file, ".jpeg") != NULL ||
			strstr(file, ".jpg") != NULL) {
		type = JPEG;
		readJPEG(file);

	} else if (strstr(file, ".png") != NULL) {
		fprintf(stderr, "ERROR: Format not supported as yet.\n");
		type = PNG;
		readPNG(file);

	} else {
		fprintf(stderr, "ERROR: Cannot read image %s.\n", file);
		exit(1);
	}

	return 0;
}
Пример #3
0
//!
//! @internal
//! @~English
//! @brief Read a netpbm file, either PAM, PGM or PPM
//!
//! The file type is determined from the magic number.
//! P5 is a PGM file. P6 is a PPM binary file, P7 is a PAM file.
//!
//! @param [in]  src        pointer to FILE stream to read
//! @param [out] width      reference to variable in which to store the image width
//! @param [out] height     reference to variable in which to store the image height
//! @param [out] components reference to variable in which to store the number of
//!                         components in an image pixel
//! @param [out] componentSize
//!                         reference to variable in which to store the size in bytes
//!                         of each component of a pixel.
//! @param [out] imageSize  reference to variable in which to store the size in bytes
//!                         of the image.
//! @param [out] pixels     reference to variable in which to store a pointer to the
//!                         image's pixels.
//!
//! @return an error indicator or SUCCESS
//!
//! @exception INVALID_FORMAT the file is not in .pam, .pgm or .ppm format
//!
//! @author Mark Callow
//!
FileResult
readNPBM(FILE* src, unsigned int& width, unsigned int& height,
         unsigned int& components, unsigned int& componentSize,
         unsigned int &imageSize, unsigned char** pixels)
{
    char line[255];
    int numvals;

    skipNonData(src);

    numvals = fscanf(src, "%3s", line);
        if (numvals == 0) {
        fprintf(stderr, "Error: PBM type string missing.\n");
        return INVALID_FORMAT;
        }

    if (strcmp(line, "P6") == 0) {
        return readPPM(src, width, height, components, componentSize, imageSize, pixels);
    } else if (strcmp(line, "P5") == 0) {
        components = 1;
        return readPGM(src, width, height, components, componentSize, imageSize, pixels);
    } else if (strcmp(line, "P7") == 0) {
        return readPAM(src, width, height, components, componentSize, imageSize, pixels);
    } else
        return INVALID_FORMAT;
}
Пример #4
0
GLImageStructure readImage(const std::string& FileName, ImageType type_hint)
{
  if (type_hint==itUnknown)
  {
    type_hint = getImageType(FileName);
  }
  switch (type_hint)
  {
    case itJPEG:
         return readJPEG(FileName);
    case itPNG:
         return readPNG(FileName);
    case itGIF:
         return readGIF(FileName);
    case itBitmap:
         return readBMP(FileName);
    case itPPM:
         return readPPM(FileName);
  }

  //no supported image here
  GLImageStructure temp_glis;
  temp_glis.setWidth(0);
  temp_glis.setHeight(0);
  temp_glis.setFormat(0);
  temp_glis.setBuffer(NULL);
  return temp_glis;
}
Пример #5
0
/**************************************************************************
	Reads in a ppm file (name given in s) and loads it as a texture.
	File should have height and width of a power of 2.  Returns 0
	if error detected, otherwise returns 1
****************************************************************************/
int setTexture(char *s)
{ 
  FILE *fin;
  if ( !(fin = fopen(s, "rb")) )  {  return 0; }
  texpat = readPPM(fin, &w, &h); /* w and h must be a power of 2 */
  if (texpat == NULL) return 0;
  glPixelStorei(GL_UNPACK_ALIGNMENT,1);
  // Uncomment one of the glTexEnvi lines below
  // (GL_MODULATE is the default)
  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
  //glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  //glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
  //glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  glTexImage2D( GL_TEXTURE_2D, /* target */ 0, /* level */
  		3, /* components */
  		w, h, /* width, height */ 0, /* border */
  		GL_RGB,  /* format */   GL_UNSIGNED_BYTE, /* type */
  		texpat);
  free(texpat); /* free the texture memory */
  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
   return 1;
}
Пример #6
0
int main(int argc , char ** argv){

    PPMImage *imageTinyCorrect;
    imageTinyCorrect = readPPM("flower_tiny_correct.ppm");
    PPMImage *imageSmallCorrect;
    imageSmallCorrect = readPPM("flower_small_correct.ppm");
    PPMImage *imageMediumCorrect;
    imageMediumCorrect = readPPM("flower_medium_correct.ppm");

    PPMImage *imageTiny;
    imageTiny = readPPM("flower_tiny.ppm");
    PPMImage *imageSmall;
    imageSmall = readPPM("flower_small.ppm");
    PPMImage *imageMedium;
    imageMedium = readPPM("flower_medium.ppm");

    printf("flower_tiny.ppm:\n");
    int pass = testImage(imageTiny, imageTinyCorrect);
    printf("flower_small.ppm:\n");
    pass = testImage(imageSmall, imageSmallCorrect);
    printf("flower_medium.ppm:\n");
    pass = testImage(imageMedium, imageMediumCorrect);

    exit(0);
}
Пример #7
0
int main(int argc, char *argv[]) {

    if( argc != 2 ) {
        printf("Too many or no one arguments supplied.\n");
    }

    double t_start, t_end;
    int i;
    char *filename = argv[1]; //Recebendo o arquivo!;

    PPMImage *image = readPPM(filename);
    PPMImage *image_output = readPPM(filename);

    t_start = rtclock();
    Smoothing_CPU_Serial(image_output, image);
    t_end = rtclock();
    // fprintf(stdout, "\n%0.6lfs\n", t_end - t_start);

    writePPM(image_output);

    free(image);
    free(image_output);
}
Пример #8
0
int main(int argc, char** argv)
{
    //Puck status text
    strcpy(text[0],"Shoot the puck!");
    strcpy(text[1],"What a goal!");
    strcpy(text[2], "Everything, but net!");
    strcpy(text[3], "The puck hits the left post!");
    strcpy(text[4], "The puck hits the right post!");
    strcpy(text[5], "The puck hits the crossbar!");
    strcpy(text[6], "Shoot it a little harder, guy!");
    
	glutInit(&argc, argv);
    glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(1000,1000);
	glutInitWindowPosition(50,50);
	glutCreateWindow("Hockey Guy");
    glEnable(GL_DEPTH_TEST);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    readPPM(BOARDS);
    generateTextures(0);
    readPPM(ICE);
    generateTextures(1);
    readPPM(NET);
    generateTextures(2);
    readPPM(STICK);
    generateTextures(3);
    readPPM(WALL);
    generateTextures(4);
    myinit();
	glutDisplayFunc(display);
    glutIdleFunc(idle);
    glutKeyboardFunc(keys);
    glutSpecialFunc(special);
	glutMainLoop();
	
	return 0;
}
Пример #9
0
void initialize () 
{
	glMatrixMode(GL_PROJECTION);
	glViewport(0, 0, 320, 320);
	GLfloat aspect = (GLfloat) 320 / 320;
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45, aspect, 0.1, 1000.0);
	glMatrixMode(GL_MODELVIEW);
	glShadeModel( GL_SMOOTH );
	glClearColor( 0.0f, 0.0f, 0.0f, 0.5f );
	glClearDepth( 1.0f );
	glEnable( GL_DEPTH_TEST );
	glDepthFunc( GL_LEQUAL );
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );

	GLfloat amb_light[] = { 0.1, 0.1, 0.1, 1.0 };
	GLfloat diffuse[] = { 0.6, 0.6, 0.6, 1 };
	GLfloat specular[] = { 0.7, 0.7, 0.3, 1 };
	glLightModelfv( GL_LIGHT_MODEL_AMBIENT, amb_light );
	glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
	glLightfv( GL_LIGHT0, GL_SPECULAR, specular );
	glEnable( GL_LIGHT0 );
	glEnable( GL_COLOR_MATERIAL );
	glShadeModel( GL_SMOOTH );
	glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE );
	glDepthFunc( GL_LEQUAL );
	glEnable( GL_DEPTH_TEST );
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0); 

	glEnable(GL_TEXTURE_2D);
	glActiveTexture(GL_TEXTURE0);
	//textureImage = readPPM("pebbles_texture.ppm");
	textureImage = readPPM("yourOwnTexture.ppm");
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	printf("%d %d \n", textureImage->x, textureImage->y);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureImage->x, textureImage->y, 0, GL_RGB, GL_UNSIGNED_BYTE, textureImage->data);
	glBindTexture(GL_TEXTURE_2D, 0);
}
Пример #10
0
GLuint loadTexture( const char * filename, int wrap )
{

    GLuint texture;
    int width, height;
    unsigned char * data = readPPM(filename, &width, &height);

    // allocate a texture name
    glGenTextures( 1, &texture );

    // select our current texture
    glBindTexture( GL_TEXTURE_2D, texture );

    // select modulate to mix texture with color for shading
    glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    // when texture area is small, bilinear filter the closest mipmap
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );

    // when texture area is large, bilinear filter the first mipmap
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

    // if wrap is true, the texture wraps over at the edges (repeat)
    //       ... false, the texture ends at the edges (clamp)
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap ? GL_REPEAT : GL_CLAMP );

    // build our texture mipmaps
    gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data );

    glBindTexture( GL_TEXTURE_2D, 0);
    // free buffer
    free( data );

    return texture;
}
Пример #11
0
/* reads a PPM image from the given filename. Initializes the alpha channel to 1.0 and the z channel to 1.0. Returns a NULL pointer if the operation fails. */
Image *image_read(char *filename) {
    int rows = 0;
    int cols = 0;
    int colors = 0;
    Pixel *image_array = readPPM(&rows, &cols, &colors, filename); // an array of pixels
    
    if (rows < 0 || cols < 0 ) {
        printf("rows: %d, cols: %d", rows, cols);
        return(NULL);
    }
    
    Image *image = image_create(rows, cols);
    for (int row=0;row<rows;row++) {
        for (int col=0;col<cols;col++) {

            image->data[row][col].rgb[0] = 256 - image_array[row*cols + col].r;
            image->data[row][col].rgb[1] = 256 - image_array[row*cols + col].g;
            image->data[row][col].rgb[2] = 256 - image_array[row*cols + col].b;
            image->data[row][col].a = 1.0;
            image->data[row][col].z = 1.0;
        }
    }
    return(image);
}
Пример #12
0
int main(int argc, char** argv) {

	PPMImage *image;
        
	if(argc > 1) {
		image = readPPM("flower.ppm");
	} else {
		image = readStreamPPM(stdin);
	}

	AccurateImage *imageUnchanged = convertImageToNewFormat(image); // save the unchanged image from input image
	AccurateImage *imageBuffer = createEmptyImage(image);
	AccurateImage *imageSmall = createEmptyImage(image);
	AccurateImage *imageBig = createEmptyImage(image);
	
	PPMImage *imageOut;
	imageOut = (PPMImage *)malloc(sizeof(PPMImage));
	imageOut->data = (PPMPixel*)malloc(image->x * image->y * sizeof(PPMPixel));

	// Process the tiny case:
	performNewIdeaIteration(imageSmall, imageUnchanged, 2);
	performNewIdeaIteration(imageBuffer, imageSmall, 2);
	performNewIdeaIteration(imageSmall, imageBuffer, 2);
	performNewIdeaIteration(imageBuffer, imageSmall, 2);
	performNewIdeaIteration(imageSmall, imageBuffer, 2);
	
	// Process the small case:
	performNewIdeaIteration(imageBig, imageUnchanged,3);
	performNewIdeaIteration(imageBuffer, imageBig,3);
	performNewIdeaIteration(imageBig, imageBuffer,3);
	performNewIdeaIteration(imageBuffer, imageBig,3);
	performNewIdeaIteration(imageBig, imageBuffer,3);
	
	// save tiny case result
	performNewIdeaFinalization(imageSmall,  imageBig, imageOut);
	if(argc > 1) {
		writePPM("flower_tiny.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}

	
	// Process the medium case:
	performNewIdeaIteration(imageSmall, imageUnchanged, 5);
	performNewIdeaIteration(imageBuffer, imageSmall, 5);
	performNewIdeaIteration(imageSmall, imageBuffer, 5);
	performNewIdeaIteration(imageBuffer, imageSmall, 5);
	performNewIdeaIteration(imageSmall, imageBuffer, 5);
	
	// save small case
	performNewIdeaFinalization(imageBig,  imageSmall,imageOut);
	if(argc > 1) {
		writePPM("flower_small.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}

	// process the large case
	performNewIdeaIteration(imageBig, imageUnchanged, 8);
	performNewIdeaIteration(imageBuffer, imageBig, 8);
	performNewIdeaIteration(imageBig, imageBuffer, 8);
	performNewIdeaIteration(imageBuffer, imageBig, 8);
	performNewIdeaIteration(imageBig, imageBuffer, 8);

	// save the medium case
	performNewIdeaFinalization(imageSmall,  imageBig, imageOut);
	if(argc > 1) {
		writePPM("flower_medium.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}
	
	// free all memory structures
	freeImage(imageUnchanged);
	freeImage(imageBuffer);
	freeImage(imageSmall);
	freeImage(imageBig);
	free(imageOut->data);
	free(imageOut);
	free(image->data);
	free(image);
	
	return 0;
}
Пример #13
0
int main(int argc, char** argv) {
	
	PPMImage *image;
    int size;
	
	if(argc > 1) {
		image = readPPM("flower.ppm");
	} else {
		image = readStreamPPM(stdin);
	}
	AccurateImage *imageAccurate1_tiny = convertImageToNewFormat(image);
	AccurateImage *imageAccurate2_tiny = convertImageToNewFormat(image);
	
    // Process the tiny case:
    size = 2; 
    performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, size);
    performNewIdeaIteration(imageAccurate1_tiny, imageAccurate2_tiny, size);
    performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, size);
    performNewIdeaIteration(imageAccurate1_tiny, imageAccurate2_tiny, size);
    performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, size);

	
	AccurateImage *imageAccurate1_small = convertImageToNewFormat(image);
	AccurateImage *imageAccurate2_small = convertImageToNewFormat(image);
	
	// Process the small case:
    size = 3;
    performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, size);
    performNewIdeaIteration(imageAccurate1_small, imageAccurate2_small, size);
    performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, size);
    performNewIdeaIteration(imageAccurate1_small, imageAccurate2_small, size);
    performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, size);

	AccurateImage *imageAccurate1_medium = convertImageToNewFormat(image);
	AccurateImage *imageAccurate2_medium = convertImageToNewFormat(image);
	
	// Process the medium case:
    size = 5;
    performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, size);
    performNewIdeaIteration(imageAccurate1_medium, imageAccurate2_medium, size);
    performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, size);
    performNewIdeaIteration(imageAccurate1_medium, imageAccurate2_medium, size);
    performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, size);

	AccurateImage *imageAccurate1_large = convertImageToNewFormat(image);
	AccurateImage *imageAccurate2_large = convertImageToNewFormat(image);
	
    size = 8;
    performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, size);
    performNewIdeaIteration(imageAccurate1_large, imageAccurate2_large, size);
    performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, size);
    performNewIdeaIteration(imageAccurate1_large, imageAccurate2_large, size);
    performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, size);

	// Save the images.
	PPMImage *final_tiny = performNewIdeaFinalization(imageAccurate2_tiny,  imageAccurate2_small);
	PPMImage *final_small = performNewIdeaFinalization(imageAccurate2_small,  imageAccurate2_medium);
	PPMImage *final_medium = performNewIdeaFinalization(imageAccurate2_medium,  imageAccurate2_large);
	
	if(argc > 1) {
		writePPM("flower_tiny.ppm", final_tiny);
		writePPM("flower_small.ppm", final_small);
		writePPM("flower_medium.ppm", final_medium);
	} else {
		writeStreamPPM(stdout, final_tiny);
		writeStreamPPM(stdout, final_small);
		writeStreamPPM(stdout, final_medium);
	}
	return 0;
}
void handle_input(char *input, img_t **in, img_t **out, img_t **original) {
#ifndef MPI
  /* Read input image, memory is automaticaly allocated. */
  img_t *read = readPPM(input);

  /* Allocate memory for output image. */
  *out = createPPM(read->w, read->h);

  /* For sequential code, the input is just what we read from file. */
  *in = read;
  *original = read;
#else
  /* Size and rank for MPI. */
  int size, rank;

  /* Array to broadcast image width and height. */
  int dim[2];

  /* Local variables for image size and number of lines to compute. */
  int w, h, extrarows, index;

  /* Declare pointer to image to read. */
  img_t *read = NULL;

  /* Need to ask MPI who we are, and how many processes there are. */
  MPI_Comm_size(MPI_COMM_WORLD, &size);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);

  /* Only one (the first) process reads the input. */
  if (rank == 0) {

    /* Read input */
    read = readPPM(input);

    /* Get size for broadcasting to others */
    dim[0] = read->w;
    dim[1] = read->h;
  }

  /* Let others know the size of the image. */
  MPI_Bcast(dim, 2, MPI_INT, 0, MPI_COMM_WORLD);

  /* Width is the same for each process. */
  w = dim[0];

  /* We divide the rows of pixels (height) over the processes. */
  h = dim[1] / size;

  /*
   *  There might be some rows left (remainder of division),
   *  so some processes must do an additional row.
   */
  extrarows = dim[1] % size;
  if (rank < extrarows) {
    h++;
  }

  /* As we know the size by now, we can create the local images */
  *in = createPPM(w, h);
  *out = createPPM(w, h);

  /* The first one sends all the processes their data. */
  if (rank == 0) {

    /* First copy data for myself. */
    memcpy((*in)->data, read->data, w * h * sizeof(pixel_t));

    /* The next send should start at this index. */
    index = w * h;

    /* Loop over all workers. */
    for (int i = 1; i < size; i++) {

      /* Calculate how many rows this worker gets */
      int height = dim[1] / size;
      if (i < extrarows) {
        height++;
      }

      /* Do the actual sending */
      MPI_Send(read->data + index, w * height * sizeof(pixel_t),
               MPI_UNSIGNED_CHAR, i, 0, MPI_COMM_WORLD);

      /* Update the index for next send. */
      index += w * height;
    }

    /* Store a pointer to the original image. */
    *original = read;

  } else {
    /* All others just receive */

    MPI_Recv((*in)->data, w * h * sizeof(pixel_t),
             MPI_UNSIGNED_CHAR, 0, 0, MPI_COMM_WORLD, NULL);
  }
#endif
}
Пример #15
0
int main(int argc, char *argv[]) {
  Pixel *image1;
  Pixel *image2;
  Pixel *image3;
  int rows, cols, colors;
  long imagesize;
  // //int intensity, avg_r, avg_g, avg_b;


  if(argc < 5) {
    printf("Usage: %s <input file_1><input file_2><input mask><output file>\n", argv[0]);
    exit(-1);
  }

  /* read in the image */
  image1 = readPPM(&rows, &cols, &colors, argv[1]);
  if(!image1) {
    fprintf(stderr, "Unable to read file_1 %s\n", argv[1]);
    exit(-1);
  }else{
    printf("successfully opened image %s\n", argv[1]);
  }

  image2 = readPPM(&rows, &cols, &colors, argv[2]);
  if(!image2) {
    fprintf(stderr, "Unable to read file_2 %s\n", argv[2]);
    exit(-1);
  }else{
    printf("successfully opened image %s\n", argv[2]);
  }

  image3 = readPPM(&rows, &cols, &colors, argv[3]);
  if(!image3) {
    fprintf(stderr, "Unable to read mask %s\n", argv[3]);
    exit(-1);
  }else{
    printf("successfully opened image %s\n", argv[3]);
  }

  /* calculate the image size */
  imagesize = (long)rows * (long)cols;

  //image1 = makeMask(image1, imagesize); // use for creating the mask
  //image1 = setBackground(image1, image2, image3, imagesize); // setting the back ground ***use either this method or "translate" method. NOT BOTH
  image1 = translate(image1, image2, image3, imagesize, cols, rows,0,0); // sets the back ground as well as translates the front image.
  //image1 = toGreyscale(image1, imagesize); // turns an image to greyscale
  image1 = toNegative(image1, imagesize); // turns an image to negative
  //image1 = horizontalBlur(image1, imagesize); // turns the  image blury



//   /* write out the resulting image */
  writePPM(image1, rows, cols, colors /* s/b 255 */, argv[4]);

//   /* free the image memory */
#if USECPP
  delete[] image;
#else
  free(image1);
  free(image2);
  free(image3);
#endif

  return(0);
}
Пример #16
0
Texture::Texture(const char* _path) {
    readPPM(_path);
}
int main( int argc, char* argv[]){
	if (argc<4){
		printf("Usage: %s image annotations output\n", argv[0] );
		return 1;
	}
	// Number of labels [use only 4 to make our lives a bit easier]
	const int M = 4;
	// Load the color image and some crude annotations (which are used in a simple classifier)
	int W, H, GW, GH;
	unsigned char * im = readPPM( argv[1], W, H );
	if (!im){
		printf("Failed to load image!\n");
		return 1;
	}
	unsigned char * anno = readPPM( argv[2], GW, GH );
	if (!anno){
		printf("Failed to load annotations!\n");
		return 1;
	}
	if (W!=GW || H!=GH){
		printf("Annotation size doesn't match image!\n");
		return 1;
	}
	// Get the labeling
	VectorXs labeling = getLabeling( anno, W*H, M );
	const int N = W*H;
	
	// Get the logistic features (unary term)
	// Here we just use the color as a feature
  Eigen::MatrixXf logistic_feature( 4, N ), logistic_transform( M, 4 );
	logistic_feature.fill( 1.f );
	for( int i=0; i<N; i++ )
		for( int k=0; k<3; k++ )
			logistic_feature(k,i) = im[3*i+k] / 255.;
	
	for( int j=0; j<logistic_transform.cols(); j++ )
		for( int i=0; i<logistic_transform.rows(); i++ )
			logistic_transform(i,j) = 0.01*(1-2.*random()/RAND_MAX);
	
	// Setup the CRF model
	DenseCRF2D crf(W, H, M);
	// Add a logistic unary term
	crf.setUnaryEnergy( logistic_transform, logistic_feature );
	
	// Add simple pairwise potts terms
	crf.addPairwiseGaussian( 3, 3, new PottsCompatibility( 1 ) );
	// Add a longer range label compatibility term
  crf.addPairwiseBilateral( 80.0f, 80.0f, 13.0f, 13.0f, 13.0f, &*im, new MatrixCompatibility::MatrixCompatibility( Eigen::MatrixXf::Identity(M,M) ) );
	
	// Choose your loss function
// 	LogLikelihood objective( labeling, 0.01 ); // Log likelihood loss
// 	Hamming objective( labeling, 0.0 ); // Global accuracy
// 	Hamming objective( labeling, 1.0 ); // Class average accuracy
// 	Hamming objective( labeling, 0.2 ); // Hamming loss close to intersection over union
	IntersectionOverUnion objective( labeling ); // Intersection over union accuracy
	
	int NIT = 5;
	const bool verbose = true;
	
  Eigen::MatrixXf learning_params( 3, 3 );
	// Optimize the CRF in 3 phases:
	//  * First unary only
	//  * Unary and pairwise
	//  * Full CRF
	learning_params<<1,0,0,
	                 1,1,0,
					 1,1,1;
	
	for( int i=0; i<learning_params.rows(); i++ ) {
		// Setup the energy
		CRFEnergy energy( crf, objective, NIT, learning_params(i,0), learning_params(i,1), learning_params(i,2) );
		energy.setL2Norm( 1e-3 );
		
		// Minimize the energy
		Eigen::VectorXf p = minimizeLBFGS( energy, 2, true );
		
		// Save the values
		int id = 0;
		if( learning_params(i,0) ) {
			crf.setUnaryParameters( p.segment( id, crf.unaryParameters().rows() ) );
			id += crf.unaryParameters().rows();
		}
		if( learning_params(i,1) ) {
			crf.setLabelCompatibilityParameters( p.segment( id, crf.labelCompatibilityParameters().rows() ) );
			id += crf.labelCompatibilityParameters().rows();
		}
		if( learning_params(i,2) )
			crf.setKernelParameters( p.segment( id, crf.kernelParameters().rows() ) );
	}
	// Return the parameters
	std::cout<<"Unary parameters: "<<crf.unaryParameters().transpose()<<std::endl;
	std::cout<<"Pairwise parameters: "<<crf.labelCompatibilityParameters().transpose()<<std::endl;
	std::cout<<"Kernel parameters: "<<crf.kernelParameters().transpose()<<std::endl;
	
	// Do map inference
	VectorXs map = crf.map(NIT);
	
	// Store the result
	unsigned char *res = colorize( map, W, H );
	writePPM( argv[3], W, H, res );
	
	delete[] im;
	delete[] anno;
	delete[] res;
}
Пример #18
0
int main() {
    PPMImage *image;
    image = readPPM("flower.ppm");


    AccurateImage *imageAccurate1_tiny = convertImageToNewFormat(image);
    AccurateImage *imageAccurate2_tiny = convertImageToNewFormat(image);

    // Process the tiny case:
    for(int colour = 0; colour < 3; colour++) {
        int size = 2; 
        performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, colour, size);
        performNewIdeaIteration(imageAccurate1_tiny, imageAccurate2_tiny, colour, size);
        performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, colour, size);
        performNewIdeaIteration(imageAccurate1_tiny, imageAccurate2_tiny, colour, size);
        performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, colour, size);
    }


    AccurateImage *imageAccurate1_small = convertImageToNewFormat(image);
    AccurateImage *imageAccurate2_small = convertImageToNewFormat(image);

    // Process the small case:
    for(int colour = 0; colour < 3; colour++) {
        int size = 3;
        performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, colour, size);
        performNewIdeaIteration(imageAccurate1_small, imageAccurate2_small, colour, size);
        performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, colour, size);
        performNewIdeaIteration(imageAccurate1_small, imageAccurate2_small, colour, size);
        performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, colour, size);
    }

    AccurateImage *imageAccurate1_medium = convertImageToNewFormat(image);
    AccurateImage *imageAccurate2_medium = convertImageToNewFormat(image);

    // Process the medium case:
    for(int colour = 0; colour < 3; colour++) {
        int size = 5;
        performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, colour, size);
        performNewIdeaIteration(imageAccurate1_medium, imageAccurate2_medium, colour, size);
        performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, colour, size);
        performNewIdeaIteration(imageAccurate1_medium, imageAccurate2_medium, colour, size);
        performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, colour, size);
    }

    AccurateImage *imageAccurate1_large = convertImageToNewFormat(image);
    AccurateImage *imageAccurate2_large = convertImageToNewFormat(image);

    // Do each color channel
    for(int colour = 0; colour < 3; colour++) {
        int size = 8;
        performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, colour, size);
        performNewIdeaIteration(imageAccurate1_large, imageAccurate2_large, colour, size);
        performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, colour, size);
        performNewIdeaIteration(imageAccurate1_large, imageAccurate2_large, colour, size);
        performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, colour, size);
    }

    // Save the images.
    PPMImage *final_tiny = performNewIdeaFinalization(imageAccurate2_tiny,  imageAccurate2_small);
    writePPM("flower_tiny_correct.ppm",final_tiny);

    PPMImage *final_small = performNewIdeaFinalization(imageAccurate2_small,  imageAccurate2_medium);
    writePPM("flower_small_correct.ppm",final_small);

    PPMImage *final_medium = performNewIdeaFinalization(imageAccurate2_medium,  imageAccurate2_large);
    writePPM("flower_medium_correct.ppm",final_medium);

}
Пример #19
0
int main(int argc, char *argv[]) {

    if (argc < 5 )
    {
        printf("\n Usage: ./denoise input.ppm output.ppm N F \n input.ppm is the name of the input file\n output.ppm is the name of the output file \n N specifies the size of the window\n F is the type of filtering");
        return 1;
    }
    const char *input = (argv[1]), *output = (argv[2]), *type = (argv[4]);

    int size = atoi(argv[3]);

    int *width, *height, *max;

    printf("Reading file %c", *input);
    clock_t start, end;
    double cpu_time_used;
    start = clock();

    RGB *readfile = readPPM(input, width, height, max);

    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("***\t %c read in %e seconds", *input, cpu_time_used);

    filter rtype;

    if ((*type) == 'A')
    {
      printf("Processing %d x %d image using %d x %d and mean filter...", *width, *height, size, size);
      rtype = MEAN;
    }
    else
    {
      printf("Processing %d x %d image using %d x %d and median filter...", *width, *height, size, size);

    }

    start = clock();

    RGB *writefile = denoiseImage (*width, *height, readfile, size, rtype);

    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("***\t image processed in %e seconds", cpu_time_used);


    printf("Writing file %c", *output);
    start = clock();

    writePPM(output, *width, *height, *max, writefile);
    printf("\n");

    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("***\t %c read in %e seconds", *output, cpu_time_used);

    /*
    deallocateBST(bst_root);
    deallocateList(list_head);
    free(A);
     */
    return 0;
}
Пример #20
0
int main( int argc, char* argv[] )
{
    //===================================================================
    // Get the command-line options.
    //===================================================================
    Options opt;
    if( !options( argc, argv , opt ) )
    {
        return 1;
    }

    // Output the options.
    std::cerr << "Using demo sequence " << opt.sequenceNumber << "." << std::endl;
    std::cerr << "Output path is: \"" << opt.outputPath << "\"." << std::endl;
    std::cerr << "Number Of Images: " << opt.nImages << std::endl;
    std::cerr << "Start frame: " << opt.startFrame << std::endl;

    std::cerr << "Blur mode: " << ( opt.blurMode == Options::kGentle ? "Gentle" : "Aggressive") << std::endl;
    std::cerr << "Blur strength: " << opt.blurStrength << std::endl;
    std::cerr << "Contribution strength: " << opt.contributionStrength << std::endl;
    std::cerr << "Kernel width: " << opt.kernelWidth << std::endl;

    // Load the images.
    std::vector< Image > images( opt.nImages );
    int frame = opt.startFrame;
    for( unsigned int i = 0; i < images.size(); ++i )
    {
        std::stringstream s;
        s << "images/image" << opt.sequenceNumber << "." << frame << ".ppm";

        if( !readPPM( s.str(), images[i] ) )
        {
            std::cerr << "Failed to open image " << s.str() << std::endl;
            return 1;
        }

        if( ++frame >= 11 )
        {
            frame = 0;
        }
    }

    //===================================================================
    // The algorithm.
    //===================================================================

    SampleSet set( images );
    const int width = set.width(), height = set.height();
    Image result( width, height );


    int kernelRadius = opt.kernelWidth > 1 ? ( opt.kernelWidth - 1 ) / 2 : 0;
    std::vector< double > srcSamples;
    for( int y = 0; y < height; ++y )
    {
        for( int x = 0; x < width; ++x )
        {
            fprintf(stderr,"\rFiltering %5.2f%% complete.", 100. * y / ( height-1 ) );

            // Loop over each channel.
            for( unsigned int c = 0; c < 3; ++c )
            {
                double destMean = set.mean( x, y, c );
                double destDeviation = set.deviation( x, y, c );
                double destVariation = set.variance( x, y, c );
                double destRange = set.max( x, y, c ) - set.min( x, y, c );

                // Loop over the neighbouring pixels.
                double weightedSum = 0.;
                double v = 0.;
                for( int ky = -kernelRadius; ky <= kernelRadius; ++ky )
                {
                    for( int kx = -kernelRadius; kx <= kernelRadius; ++kx )
                    {
                        // Don't include the pixel being sampled in our calculations as we are
                        // summing the deviations from it and doing so will bias our results.
                        if( ky == 0 && kx == 0 )
                        {
                            continue;
                        }

                        // Gather information on the source pixel's samples.
                        srcSamples = set.samples( x + kx, y + ky, c );
                        double srcMin = set.min( x + kx, y + ky, c );
                        double srcMax = set.max( x + kx, y + ky, c );
                        double srcMean = set.mean( x + kx, y + ky, c );
                        double srcDeviation = set.deviation( x + kx, y + ky, c );
                        double srcVariation = set.variance( x + kx, y + ky, c );
                        double srcRange = set.max( x + kx, y + ky, c ) - set.min( x + kx, y + ky, c );

                        if( srcVariation == 0 && srcSamples[0] == 0. ) continue;

                        // A gaussian falloff that weights contributing samples which are closer to the pixel being filtered higher.
                        /// \todo Intuitive falloff parameters need to be added to the distance weight or at least a suitable curve found.
                        double distanceWeight = gaussian( sqrt( kx*kx + ky*ky ) / sqrt( kernelRadius*kernelRadius + kernelRadius*kernelRadius ), 0., .7, false );

                        // Similarity weight.
                        // This weight defines a measure of how similar the set of contributing samples is to the pixel being filtered.
                        // By itself it will produce a smart blur of sorts which is then attenuated by the variance of the source samples in the process of weighted offsets.
                        // Changing this value will effect how aggressive the filtering is.
                        double similarity;
                        if( opt.blurMode == Options::kAggressive )
                        {
                            similarity = ( srcMean - destMean ) * ( srcRange - destRange );
                        }
                        else
                        {
                            similarity = ( srcMean - destMean );
                        }
                        similarity *= similarity;

                        // Temporal weight.
                        // Weight the contribution using a function in the range of 0-1 which weights the importance of the
                        // contributing sample according to how close it is in time to the current time.
                        double time = 1.; // \todo: implement this! Example functions are Median, Gaussian, etc.

                        // Loop over each of the neighbouring samples.
                        for( unsigned int i = 0; i < srcSamples.size(); ++i )
                        {
                            // The contribution weight extends the range of allowed samples that can influence the pixel being filtered.
                            // It is simply a scaler that increases the width of the bell curve that the samples are weighted against.
                            double contribution = gaussian( srcSamples[i], destMean, destDeviation * ( 1 + opt.contributionStrength ) ) * gaussian( srcSamples[i], srcMean, srcDeviation );
                            contribution = contribution * ( 1. - opt.blurStrength ) + opt.blurStrength;

                            // This weight is a step function with a strong falloff close to the limits. However, it will never reach 0 so that the sample is not excluded.
                            // By using this weight the dependency on the limiting samples is much less which reduces the effect of sparkling artefacts.
                            double limitWeight = srcSamples.size() <= 2 ? 1. : softStep( srcSamples[i], srcMin, srcMax );

                            // Combine the weights together and normalize to the range of 0-1.
                            double weight = pow( M_E, -( similarity / ( contribution * srcVariation * time * distanceWeight * limitWeight ) ) );
                            weight = ( isnan( weight ) || isinf( weight ) ) ? 0. : weight;

                            // Sum the offset.
                            v += ( srcSamples[i] - destMean ) * weight;

                            // Sum the weight.
                            weightedSum += weight;
                        }
                    }
                }

                if( weightedSum == 0. || destVariation <= 0. )
                {
                    result.writeable( x, y )[c] = destMean;
                }
                else
                {
                    result.writeable( x, y )[c] = destMean + ( v / weightedSum );
                }
            }
        }
    }

    bool success = false;
    if( opt.extension == "bmp" )
    {
        success = writeBMP( opt.outputPath.c_str(), result );
    }
    else
    {
        success = writePPM( opt.outputPath.c_str(), result );
    }

    if( !success )
    {
        std::cerr << "Failed to write image." << std::endl;
        return 1;
    }

    return 0;
}
Пример #21
0
int main(int argc, char *argv[]) {

  Pixel *image;
  int rows, cols, colors;
  long imagesize;
  long i;
  int gain;
  unsigned char *mask = NULL;
  unsigned char *grown = NULL;
  unsigned char *shrunk = NULL;
  unsigned char *median = NULL;
  char *inputfile;

  if (argc != 2) {
    printf("Usage: %s <input file>\n", argv[0]);
    exit(-1);
  }

  inputfile = argv[1];
  gain = 2;

  /* read in the image */
  image = readPPM(&rows, &cols, &colors, inputfile);
  if (!image) {
    fprintf(stderr, "Unable to read %s\n", inputfile);
    exit(-1);
  }

  /* calculate the image size */
  imagesize = (long)rows * (long)cols;
  mask = (unsigned char*) malloc(sizeof(unsigned char) * imagesize);
  grown = (unsigned char*) malloc(sizeof(unsigned char) * imagesize);
  shrunk = (unsigned char*) malloc(sizeof(unsigned char) * imagesize);
  median = (unsigned char*) malloc(sizeof(unsigned char) * imagesize);

  /* mask the image */
  for (i=0; i<imagesize; i++) {
    if (image[i].r > (gain * image[i].g)) {
      mask[i] = BACKGROUND;
    }
    else {
      mask[i] = FOREGROUND;
    }
  } 

  /* manipulate the images */
  grow(mask, grown, rows, cols);
  shrink(mask, shrunk, rows, cols);
  medianify(mask, median, rows, cols);

  /* write out the files */
  writePGM(mask, rows, cols, INTENSITIES, "masked.pgm");
  writePGM(grown, rows, cols, INTENSITIES, "grown.pgm");
  writePGM(shrunk, rows, cols, INTENSITIES, "shrunk.pgm");
  writePGM(median, rows, cols, INTENSITIES, "median.pgm");

  /* free the image memory */
  free(image);
  free(mask);
  free(grown);
  free(shrunk);
  free(median);

  return(0);
}
Пример #22
0
/**
 * Lee y genera las texturas utilizadas
 */
void genTexturas() {
	paleta = loadPalInt("paletas/landcolor3.ppm", 256);
	paletaf = intPal2Float(paleta, 256);
	paleta_agua = loadPalInt("paletas/watercolor7.ppm", 256);
	paleta_aguaf = intPal2Float(paleta_agua, 256);
	paleta_grass = loadPalInt("paletas/grasscolor2.ppm", 256);
	paleta_grassf = intPal2Float(paleta_grass, 256);
	tree = readPPM("paletas/tree.ppm");
	snowtree = readPPM("paletas/treesnow.ppm");
	treealpha = readPGM("paletas/treealpha.pgm");
	datatree = genTextIntAlpha(tree, treealpha, 256);
	datasnowtree = genTextIntAlpha(snowtree, treealpha, 256);
	paletanubes = loadPalInt("paletas/skyalpha.ppm", 256);
	nubesalpha = skyalpha3D(paletanubes, FRAMES_NUBES, int((nubosidad)*128.0), 256);
	nubes = new rgbint*[256]; // nubes blancas
	for (int i=0; i<256; i++){
		nubes[i] = new rgbint[256];
		for (int j=0; j<256; j++){
			nubes[i][j].r = 255;
			nubes[i][j].g = 255;
			nubes[i][j].b = 255;		
		}
	}
	datanubes = new int*[FRAMES_NUBES];
	for (int i=0; i<FRAMES_NUBES; i++){
		datanubes[i] = genTextIntAlpha(nubes,nubesalpha[i],256);
	}
	//writePGMint("../../nubes3D.pgm", nubesalpha[0], 256);
	
	// Genera los nombres de textura 
	glGenTextures(15, texNames);
	glBindTexture(GL_TEXTURE_2D, texNames[ARBOL]);
	genText(datatree, false, 256);
	
	glBindTexture(GL_TEXTURE_2D, texNames[ARBOLNIEVE]);
	genText(datasnowtree,false, 256);	
	
	for (int i=0; i<FRAMES_NUBES; i++){
		glBindTexture(GL_TEXTURE_2D, texNames[NUBES+i]);
		genText(datanubes[i], true, 256);		
	}
	
	brujula = new rgbint*[128]; // brujula negra
	for (int i=0; i<128; i++){
		brujula[i] = new rgbint[128];
		for (int j=0; j<128; j++){
			brujula[i][j].r = 0;
			brujula[i][j].g = 0;
			brujula[i][j].b = 0;		
		}
	}
	brujulaalpha = readPGM("paletas/brujulaalpha.pgm");
	databrujula = genTextIntAlpha(brujula, brujulaalpha, 128);
	aguja = readPPM("paletas/aguja.ppm");
	agujaalpha = readPGM("paletas/agujaalpha.pgm");
	dataaguja = genTextIntAlpha(aguja, agujaalpha, 128);
	
	glBindTexture(GL_TEXTURE_2D, texNames[BRUJULA]);
	genText(databrujula,false, 128);	
	
	glBindTexture(GL_TEXTURE_2D, texNames[AGUJA]);
	genText(dataaguja,false, 128);	
	
}
int main( int argc, char* argv[]){
	if (argc<4){
		printf("Usage: %s image annotations output\n", argv[0] );
		return 1;
	}
	// Number of labels
	const int M = 21;
	// Load the color image and some crude annotations (which are used in a simple classifier)
	int W, H, GW, GH;
	unsigned char * im = readPPM( argv[1], W, H );
	if (!im){
		printf("Failed to load image!\n");
		return 1;
	}
	unsigned char * anno = readPPM( argv[2], GW, GH );
	if (!anno){
		printf("Failed to load annotations!\n");
		return 1;
	}
	if (W!=GW || H!=GH){
		printf("Annotation size doesn't match image!\n");
		return 1;
	}
	
	/////////// Put your own unary classifier here! ///////////
  Eigen::MatrixXf unary = computeUnary( getLabeling( anno, W*H, M ), M );
	///////////////////////////////////////////////////////////
	
	// Setup the CRF model
	DenseCRF2D crf(W, H, M);
	// Specify the unary potential as an array of size W*H*(#classes)
	// packing order: x0y0l0 x0y0l1 x0y0l2 .. x1y0l0 x1y0l1 ...
	crf.setUnaryEnergy( unary );
	// add a color independent term (feature = pixel location 0..W-1, 0..H-1)
	// x_stddev = 3
	// y_stddev = 3
	// weight = 3
	crf.addPairwiseGaussian( 3, 3, new PottsCompatibility( 3 ) );
	// add a color dependent term (feature = xyrgb)
	// x_stddev = 60
	// y_stddev = 60
	// r_stddev = g_stddev = b_stddev = 20
	// weight = 10
	crf.addPairwiseBilateral( 80, 80, 13, 13, 13, im, new PottsCompatibility( 10 ) );
	
	// Do map inference
// 	Eigen::MatrixXf Q = crf.startInference(), t1, t2;
// 	printf("kl = %f\n", crf.klDivergence(Q) );
// 	for( int it=0; it<5; it++ ) {
// 		crf.stepInference( Q, t1, t2 );
// 		printf("kl = %f\n", crf.klDivergence(Q) );
// 	}
// 	VectorXs map = crf.currentMap(Q);
	VectorXs map = crf.map(5);
	// Store the result
	unsigned char *res = colorize( map, W, H );
	writePPM( argv[3], W, H, res );
	
	delete[] im;
	delete[] anno;
	delete[] res;
}
Пример #24
0
// Host code
int main(int argc, char** argv)
{
    ParseArguments(argc, argv);
	
	float s_SobelMatrix[25];  
	s_SobelMatrix[0] = 1;
	s_SobelMatrix[1] = 2;
	s_SobelMatrix[2]= 0;
	s_SobelMatrix[3] = -2;
	s_SobelMatrix[4] = -1;
	s_SobelMatrix[5] = 4;
	s_SobelMatrix[6] = 8;
	s_SobelMatrix[7] = 0;
	s_SobelMatrix[8] = -8;
	s_SobelMatrix[9] = -4;
	s_SobelMatrix[10] = 6;
	s_SobelMatrix[11] = 12;
	s_SobelMatrix[12] = 0;
	s_SobelMatrix[13] = -12;
	s_SobelMatrix[14] = -6;
	s_SobelMatrix[15] = 4;
	s_SobelMatrix[16] = 8; 
	s_SobelMatrix[17] = 0;
	s_SobelMatrix[18] = -8;
	s_SobelMatrix[19] =-4;
	s_SobelMatrix[20] =1;
	s_SobelMatrix[21] =2;
	s_SobelMatrix[22] =0;
	s_SobelMatrix[23] =-2;
	s_SobelMatrix[24] =-1;
	
    unsigned char *palete = NULL;
    unsigned char *data = NULL, *out = NULL;
    PPMImage *input_image=NULL, *output_image=NULL;
    output_image = (PPMImage *)malloc(sizeof(PPMImage));
    input_image = readPPM(PPMInFileL);
    printf("Running %s filter\n", Filter);
    out = (unsigned char *)malloc();

    printf("Computing the CPU output\n");
    printf("Image details: %d by %d = %d , imagesize = %d\n", input_image->x, input_image->y, input_image->x * input_image->y, input_image->x * input_image->y);
    
	cutilCheckError(cutStartTimer(time_CPU));
	if(FilterMode == SOBEL_FILTER){
	printf("Running Sobel\n");
	CPU_Sobel(intput_image->data, output_image, input_image->x, input_image->y);
	}
	else if(FilterMode == HIGH_BOOST_FILTER){
	printf("Running boost\n");
	CPU_Boost(data, out, dib.width, dib.height);
	}
	cutilCheckError(cutStopTimer(time_CPU));
	if(FilterMode == SOBEL_FILTER || FilterMode == SOBEL_FILTER5)
    BitMapWrite("CPU_sobel.bmp", &bmp, &dib, out, palete);
	
	else if(FilterMode == AVERAGE_FILTER)
	BitMapWrite("CPU_average.bmp", &bmp, &dib, out, palete);
	
	else if(FilterMode == HIGH_BOOST_FILTER)
	BitMapWrite("CPU_boost.bmp", &bmp, &dib, out, palete);
	
    printf("Done with CPU output\n");
	printf("CPU execution time %f \n", cutGetTimerValue(time_CPU));
	
	
    printf("Allocating %d bytes for image \n", dib.image_size);
	
    cutilSafeCall( cudaMalloc( (void **)&d_In, dib.image_size*sizeof(unsigned char)) );
    cutilSafeCall( cudaMalloc( (void **)&d_Out, dib.image_size*sizeof(unsigned char)) );
    
	// creating space for filter matrix
	cutilSafeCall( cudaMalloc( (void **)&sobel_matrix, 25*sizeof(float)) );
	
	cutilCheckError(cutStartTimer(time_mem));
	
	cudaMemcpy(d_In, data, dib.image_size*sizeof(unsigned char), cudaMemcpyHostToDevice);
	
	cudaMemcpy(sobel_matrix, s_SobelMatrix, 25*sizeof(float), cudaMemcpyHostToDevice);
	
	cutilCheckError(cutStopTimer(time_mem));
    
	FilterWrapper(data, dib.width, dib.height);

    // Copy image back to host
	
	cutilCheckError(cutStartTimer(time_mem));
    cudaMemcpy(out, d_Out, dib.image_size*sizeof(unsigned char), cudaMemcpyDeviceToHost);
	cutilCheckError(cutStopTimer(time_mem));
	
	printf("GPU execution time %f Memtime %f \n", cutGetTimerValue(time_GPU), cutGetTimerValue(time_mem));
    printf("Total GPU = %f \n", (cutGetTimerValue(time_GPU) + cutGetTimerValue(time_mem)));
	// Write output image   
    BitMapWrite(BMPOutFile, &bmp, &dib, out, palete);

    Cleanup();
}