I36 Answer ― Image Addition


/* Add Images */
void addImages( image imgA, image imgB, image *imgC, double A, double B )
{
  int r, c, a, b, p ;

  /* construct an image structure of the appropriate size */
  if ( !newImage( imgC, imgA.nrows, imgA.ncols ) )
  {
    printf("addImages(): newImage failed\n" );
    exit( EXIT_FAILURE );
  }

  for ( r=0; r<imgA.nrows; r++ )
    for ( c=0; c<imgA.ncols; c++ )
    {
      a = getPixel( imgA, r, c ) ;
      b = getPixel( imgB, r, c ) ;
      p = (int)(A*a + B*b);
      if ( p<0 ) p = 0;
      if ( p>255) p = 255;
      setPixel( *imgC, r, c, (unsigned char)p );
    }
}

int main ( int argc, char* argv[] )
{
  image imgA, imgB, imgC;
  double scaleA, scaleB;
  
  if ( argc != 6 )
  {
    printf( "addImage imageA scaleA imageB scaleB sumImage\n" );
    exit( EXIT_FAILURE );
  }
  
  /* read in the  images */
  readPGMimage( &imgA, argv[1] );
  readPGMimage( &imgB, argv[3] );

  scaleA = atof( argv[2] );
  scaleB = atof( argv[4] );
  
  /* add the images */
  addImages( imgA, imgB, &imgC, scaleA, scaleB );
  
  /* write the result to disk and free memory */
  writePGMimage( imgC, argv[5] );
  freeImage( &imgA );
  freeImage( &imgB );
  freeImage( &imgC );
  
}


Comments: The number of rows and columns is taken from image A. If imageB has fewer rows or columns than image A, there will be problems. You may wish to put in more error checking than the above program has.