CSE 576: Image UnderstandingAutumn 1998Instructor: Linda Shapiro |
The Unix manpages for the PPM file format and the PGM file format are here.
Here is a sample of C code that will read the header of a PPM/PGM file:
This will set type to the magic number of the file, and set width, height, and maxval appropriately.char buffer[80]; int phase = 0; int type, maxval, width, height; int j; FILE *f = fopen( <image filename here>, "rb" ); 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; }