#include <stdlib.h>
#include <stdio.h>
#include "../basicImage.c"
void pickAverage( image img, image smooth )
{
int r, c, sum, avg, min, best;
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 );
}
/* For each 3x3 neighborhood */
for ( r=1; r<img.nrows-1; r++ )
for ( c=1; c<img.ncols-1; c++ )
{
/* Compute the average */
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 );
avg = sum/9;
/* Find the pixel closest to the average */
value=getPixel( img, r-1, c-1 );
min=abs(value-avg); best=value;
value=getPixel( img, r-1, c );
if ( abs(value-avg) < min ) { min=abs(value-avg); best=value;}
value=getPixel( img, r-1, c+1 );
if ( abs(value-avg) < min ) { min=abs(value-avg); best=value;}
value=getPixel( img, r , c-1 );
if ( abs(value-avg) < min ) { min=abs(value-avg); best=value;}
value=getPixel( img, r , c );
if ( abs(value-avg) < min ) { min=abs(value-avg); best=value;}
value=getPixel( img, r , c+1 );
if ( abs(value-avg) < min ) { min=abs(value-avg); best=value;}
value=getPixel( img, r+1, c-1 );
if ( abs(value-avg) < min ) { min=abs(value-avg); best=value;}
value=getPixel( img, r+1, c );
if ( abs(value-avg) < min ) { min=abs(value-avg); best=value;}
value=getPixel( img, r+1, c+1 );
if ( abs(value-avg) < min ) { min=abs(value-avg); best=value;}
/* replace the central pixel with the one closest to the average */
setPixel( smooth, r, c, best );
}
}
int main ( int argc, char* argv[] )
{
image img, smimg;
if ( argc != 3 )
{
printf( "smoothAverage 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 */
pickAverage( img, smimg );
/* write the image to disk and free memory */
writePGMimage( smimg, argv[2] );
freeImage( &img );
freeImage( &smimg );
}
Comments: