I47 Answer ― Repeated Smoothing


/* Puzzle47.c -- Repeatedly Smooth 3x3 with Edge Handling
|
|
*/
#include <stdlib.h>
#include <stdio.h>
#include "../basicImage.c"

void smoothImage( image img, image smooth )
{
  int r, ri, c, ci, sum, count;
  unsigned char value ;

  /* Find all neighborhood averages */
  for ( r=0; r<img.nrows; r++ )
    for ( c=0; c<img.ncols; c++ )
    {
      sum = 0; count = 0;
      for ( ri= -1; ri<=1; ri++ )
        if ( r+ri >=0 && r+ri < img.nrows )
          for ( ci= -1; ci<=1; ci++ )
            if ( c+ci >=0 && c+ci < img.ncols )
            {
              sum += getPixel( img, r+ri, c+ci );
              count++ ;
            }

      setPixel( smooth, r, c, sum/count );
    }
}

int main ( int argc, char* argv[] )
{
  image img, smimg;
  int j, N;
  
  if ( argc != 4 )
  {
    printf( "smoothRepeat oldImage smoothImage N\n" );
    system( "pause" );
    exit( EXIT_FAILURE );
  }

  N = atoi( argv[3] );
  /* read in the image */
  readPGMimage( &img, argv[1] );

  /* create a blank image */
  newImage( &smimg, img.nrows, img.ncols );

  /* repeatedly smooth the image */
  /* img and sming trade roles each time */
  for ( j=1; j<=N; j++ )
  {
    if ( j%2 == 1 )
      smoothImage( img, smimg );
    else
      smoothImage( smimg, img );
  }
  
  /* write the image to disk and free memory */
  if ( N%2 == 1 )
    writePGMimage( smimg, argv[2] );
  else
    writePGMimage(   img, argv[2] );

  freeImage( &img );
  freeImage( &smimg );
}


Comments: