/* Author: Jonathan Hardy File: thresh.cc This file reads in a binary PGM file and thresholds out pixels below a minimum and above a maximum, then writes the news image out to a new PGM file. */ #include #include #include #include FILE *ptr; // Image file FILE *threshptr; // Output file void main(int argc, char**argv) { char fname[13]; // Image filename char threshname[18]; // Output filename char width[4], height[4], numcol[4]; // Image information char Type[3]; // Image type (P5) int r, c, data; // Counters and image data variable char temp[100]; // Variable for input comment lines char comment[17]; // Variable for output comment strcpy(fname, argv[1]); // Get filename from command line strcat(fname, ".pgm"); // Append filename with ".pgm" const int ulimit = atoi(argv[2]); // Get upper threshold const int llimit = atoi(argv[3]); // Get lower threshold ptr = fopen(fname, "rb"); // Open image file fread(&Type, 3, 1, ptr); // Get image type fread(&width, 4, 1, ptr); // If no comment lines, get width while (width[0] == '#'){ // Otherwise, ignore comment lines fgets(temp, 100, ptr); // and get width fread(&width, 4, 1, ptr); } fread(&height, 4, 1, ptr); // Get height const int WIDTH = atoi(width); const int HEIGHT = atoi(height); int ImgArray[HEIGHT][WIDTH]; // Create image array fread(&numcol, 4, 1, ptr); // Get number of colors (255) for (r = 0; r < HEIGHT; r++){ // Get image data and threshold it for (c = 0; c < WIDTH; c++){ data = fgetc(ptr); if ((data < llimit) || (data > ulimit)) ImgArray[r][c] = 0; else ImgArray[r][c] = 90; } } fclose(ptr); // Close image file /* The following section writes out the thresholded image to a new PGM file. It uses the same file header data as the image file. */ strcpy(threshname, argv[1]); strcat(threshname, "_thrsh.pgm"); threshptr = fopen(threshname, "wb"); fwrite(&Type, 3, 1, threshptr); comment = "# New pgm file.\n"; fwrite(&comment, 16, 1, threshptr); fwrite(&width, 4, 1, threshptr); fwrite(&height, 4, 1, threshptr); fwrite(&numcol, 4, 1, threshptr); for (r = 0; r < HEIGHT; r++){ for (c = 0; c < WIDTH; c++){ fputc(ImgArray[r][c], threshptr); } } fclose(threshptr); }