#include <stdlib.h> #include <stdio.h> #include "../basicColorImage.c" void toGray( colorImage cimg, colorImage gimg) { int r, c, avg; pixel pix; for ( r=0; r<cimg.nrows; r++ ) for ( c=0; c<cimg.ncols; c++ ) { pix = getColorPixel( cimg, r, c ) ; avg = (pix.red + pix.grn + pix.blu)/3; pix.red = avg; pix.grn = avg; pix.blu = avg; setColorPixel( gimg, r, c, pix ); } } int main ( int argc, char* argv[] ) { colorImage cimg; colorImage gimg; if ( argc != 3 ) { printf("PPMtoGrayPPM oldImage.ppm newImage.ppm\n"); system( "pause" ); exit( EXIT_FAILURE ); } /* read in the old image */ readPPMimage( &cimg, argv[1]); /* create empty color image */ if ( newColorImage( &gimg, cimg.nrows, cimg.ncols ) == NULL ) { printf(">>error<< newColorImage can't allocate memory\n"); exit( EXIT_FAILURE ); } /* fill in gray level image */ toGray( cimg, gimg ) ; /* write the image to disk and free memory */ writePPMimage( gimg, argv[2]); freeColorImage( &cimg ); freeColorImage( &gimg ); }
Comments: The average color value will always be less than or equal any of the three RGB values for a pixel, so overflow (values above 255) will never happen.