91 Answer ― Swap Colors


#include <stdlib.h>
#include <stdio.h>
#include "../basicColorImage.c"

/* The string rgb shows what color from the old image
   should go into the color for the new image. For
   eg. "BRG" means blue goes to red, red goes to
   green, and green goes to blue.

   '0'  means to set all the pixels of the corresponding
   channel to black. For eg. "B0R" means to swap blue
   and red, and to set green to zero.
*/
void swapColors( colorImage img, char *rgb )
{
  int r, c;
  pixel pix;
  unsigned char red, grn, blu;

  for ( r=0; r<img.nrows; r++ )
    for ( c=0; c<img.ncols; c++ )
    {
      pix = getColorPixel( img, r, c ) ;
      red = pix.red; grn = pix.grn; blu = pix.blu;

      if ( rgb[0] == 'G' )
        pix.red = grn;
      else if ( rgb[0] == 'B' )
        pix.red = blu;
      else if ( rgb[0] == '0' )
        pix.red = 0;

      if ( rgb[1] == 'R' )
        pix.grn = red;
      else if ( rgb[1] == 'B' )
        pix.grn = blu;
      else if ( rgb[1] == '0' )
        pix.grn = 0;

      if ( rgb[2] == 'R' )
        pix.blu = pix.red;
      else if ( rgb[2] == 'G' )
        pix.blu = grn;
      else if ( rgb[2] == '0' )
        pix.blu = 0;

      setColorPixel( img, r, c, pix );
    }
}

int main ( int argc, char* argv[] )
{
  colorImage  img;
  double factor ;

  if ( argc != 4 )
  {
    printf("swapColors oldImage newImage RGB-permuted\n");
    system( "pause" );
    exit( EXIT_FAILURE );
  }

  /* read in the old image */
  readPPMimage( &img, argv[1]);

  /* add in the constant value */
  swapColors( img, argv[3] ) ;

  /* write the image to disk and free memory */
  writePPMimage( img, argv[2]);
  freeColorImage( &img );
}


Comments: