/* * usage: thresh * * thresholds the input file ("-" for stdin), producing a binary * PGM image. all pixels between lo and hi inclusive become white; * all others become black. */ #include #include #include #include #include #include #include using namespace std; void write_pgm( FILE* f, int width, int height, unsigned char* data ); unsigned char* read_pgm( char* filename, int* width, int* height ); main( int argc, char **argv ) { int iwidth, iheight; unsigned char* image; int i; int lo, hi; if ( argc != 4 ) { fprintf( stderr, "usage: %s lo hi imagefile\n", argv[0] ); exit( 1 ); } lo = atoi( argv[1] ); hi = atoi( argv[2] ); image = read_pgm( argv[3], &iwidth, &iheight ); if ( image == NULL ) { fprintf( stderr, "error reading image file.\n" ); exit( 1 ); } for ( i = 0; i < iwidth*iheight; ++i ) { if ( image[i] >= lo && image[i] <= hi ) image[i] = 255; else image[i] = 0; } write_pgm( stdout, iwidth, iheight, image ); } unsigned char* read_pgm( char* filename, int* width, int* height ) { char buffer[80]; int phase = 0; int type, maxval; int j; unsigned char* data; FILE* f; if ( strcmp( filename, "-" ) == 0 ) { f = stdin; } else { f = fopen( filename, "rb" ); if ( f == NULL ) return NULL; } while ( phase < 4 ) { fgets( buffer, 80, f ); if ( buffer[0] == '#' ) continue; switch( phase ) { case 0: j = sscanf( buffer, "P%d %d %d %d\n", &type, width, height, &maxval ); break; case 1: j = sscanf( buffer, "%d %d %d\n", width, height, &maxval ); break; case 2: j = sscanf( buffer, "%d %d\n", height, &maxval ); break; case 3: j = sscanf( buffer, "%d\n", &maxval ); break; case 4: j = 0; break; } phase += j; } if ( type != 5 ) { fprintf( stderr, "bad input image format.\n" ); return NULL; } data = (unsigned char*)malloc ( *width * *height ); fread( data, *width * *height, 1, f ); fclose( f ); return data; } void write_pgm( FILE* f, int width, int height, unsigned char* data ) { fprintf( f, "P5\n%d %d\n%d\n", width, height, 255 ); fwrite( data, width*height, 1, f ); fclose( f ); }