#include <stdlib.h> #include <stdio.h> #include <math.h> #include "basicImage.c" void smoothImage( image img, image smooth ) { int r, c, sum; unsigned char value ; /* Copy edge pixels from input image to output image */ for ( r=0; r<img.nrows; r++ ) { value = getPixel( img, r, 0 ) ; setPixel( smooth, r, 0, value ); value = getPixel( img, r, img.ncols-1 ) ; setPixel( smooth, r, img.ncols-1 , value ); } for ( c=0; c<img.ncols; c++ ) { value = getPixel( img, 0, c ) ; setPixel( smooth, 0, c, value ); value = getPixel( img, img.nrows-1, c ) ; setPixel( smooth, img.nrows-1, c, value ); } /* Fill in the center with neighborhood averages */ for ( r=1; r<img.nrows-1; r++ ) for ( c=1; c<img.ncols-1; c++ ) { sum = getPixel( img, r-1, c-1 ); sum += getPixel( img, r-1, c ); sum += getPixel( img, r-1, c+1 ); sum += getPixel( img, r , c-1 ); sum += getPixel( img, r , c ); sum += getPixel( img, r , c+1 ); sum += getPixel( img, r+1, c-1 ); sum += getPixel( img, r+1, c ); sum += getPixel( img, r+1, c+1 ); setPixel( smooth, r, c, sum/9 ); } } int main ( int argc, char* argv[] ) { image img, smimg; if ( argc != 3 ) { printf( "smooth oldImage smoothImage\n" ); system( "pause" ); exit( EXIT_FAILURE ); } /* read in the image */ readPGMimage( &img, argv[1] ); /* create a blank image */ newImage( &smimg, img.nrows, img.ncols ); /* fill in values for the new image */ smoothImage( img, smimg ); /* write the image to disk and free memory */ writePGMimage( smimg, argv[2] ); freeImage( &img ); freeImage( &smimg ); }
Comments: You may wish to replace the following
sum = getPixel( img, r-1, c-1 ); sum += getPixel( img, r-1, c ); sum += getPixel( img, r-1, c+1 ); sum += getPixel( img, r , c-1 ); sum += getPixel( img, r , c ); sum += getPixel( img, r , c+1 ); sum += getPixel( img, r+1, c-1 ); sum += getPixel( img, r+1, c ); sum += getPixel( img, r+1, c+1 );
with two for
loops.