I45 Answer ― R x C Neighborhood


/* Puzzle45.c -- Smooth an image using an R by C neighborhood */

#include <stdlib.h>
#include <stdio.h>
#include "basicImage.c"

void smoothRxCImage( image img, image smooth, int nRows, int nCols )
{
  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= -nRows/2; ri<=nRows/2; ri++ )
        if ( r+ri >=0 && r+ri < img.nrows )
          for ( ci= -nCols/2; ci<=nCols/2; 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 nRows, nCols ; /* Neighborhood Rows and Columns */
  
  if ( argc != 5 )
  {
    printf( "smoothRxC oldImage smoothImage neighborhoodRows neighborhoodCols\n" );
    exit( EXIT_FAILURE );
  }
  
  nRows = atoi( argv[3] );
  if ( nRows <= 0 )
  {
    printf( "Rows in neighborhood must be greater than zero\n" );
    exit( EXIT_FAILURE );
  }

  nCols = atoi( argv[4] );
  if ( nCols <= 0 )
  {
    printf( "Cols in neighborhood must be greater than zero\n" );
    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 */
  smoothRxCImage( img, smimg, nRows, nCols );
  
  /* write the image to disk and free memory */
  writePGMimage( smimg, argv[2] );
  freeImage( &img );
  freeImage( &smimg );
}

Comments: