CSE 576: Image Understanding

Autumn 1998

Instructor: Linda Shapiro
TA: Doug Zongker

PPM/PGM image file formats

All the course software will use the PPM/PGM image file format (PPM is for color images; PGM is for grayscale images). Mostly we will be using grayscale images.

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:

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;
This will set type to the magic number of the file, and set width, height, and maxval appropriately.