/* ppmtopgm.c - convert a portable pixmap to a portable graymap ** ** Copyright (C) 1989 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. */ #include "ppm.h" #include "pgm.h" #include "lum.h" int main( int argc, char* argv[] ) { FILE* ifp; pixel* pixelrow; register pixel* pP; gray* grayrow; register gray* gP; int rows, cols, format, row; register int col; pixval maxval; ppm_init( &argc, argv ); if ( argc > 2 ) pm_usage( "[ppmfile]" ); if ( argc == 2 ) ifp = pm_openr( argv[1] ); else ifp = stdin; ppm_readppminit( ifp, &cols, &rows, &maxval, &format ); pgm_writepgminit( stdout, cols, rows, maxval, 0 ); pixelrow = ppm_allocrow( cols ); grayrow = pgm_allocrow( cols ); for ( row = 0; row < rows; ++row ) { ppm_readppmrow( ifp, pixelrow, cols, maxval, format ); if ( maxval <= 255 ) /* Use fast approximation to 0.299 r + 0.587 g + 0.114 b. */ for ( col = 0, pP = pixelrow, gP = grayrow; col < cols; ++col, ++pP, ++gP ) *gP = (gray) ( ( times77[PPM_GETR( *pP )] + times150[PPM_GETG( *pP )] + times29[PPM_GETB( *pP )] ) >> 8 ); else /* Can't use fast approximation, so fall back on floats. */ for ( col = 0, pP = pixelrow, gP = grayrow; col < cols; ++col, ++pP, ++gP ) *gP = (gray) ( PPM_LUMIN( *pP ) + 0.5 ); pgm_writepgmrow( stdout, grayrow, cols, maxval, 0 ); } pm_closer( ifp ); pm_closew( stdout ); exit( 0 ); }