Victor Image Processing Library Sample Code

Reorganizing the Palette

To reorganize the palette convert it to a hue-saturation-value (HSV) table and sort by hue. Change the HSV table back into an RGB palette and match the original image to the rearranged palette. The image will appear identical to the original, but the palette will have the colors in the new order.

Original palette
Original palette

Reorganized palette      
Reorganized palette
sorted by hue
Swatch of embroidered fabric
Original and sorted palettes Scanned swatch of embroidered fabric


In the example function below, the image's palette is converted into an HSV table and sorted by hue. The sorted HSV table is then converted back into an RGB palette and a new image is created in which the original image pixels are matched to the new palette. The original image is replaced by the new one.

Reorganize the Palette - the Source Code

Requires Victor Image Processing Library for Windows v 4.1x or higher.
int __cdecl compare_hsv(const void *hsv1, const void *hsv2);
// Sort palette by hue, saturation, value
int reorganize_palette(imgdes *srcimg, imgdes *resimg)
{
   imgdes tmpres;
   int cols, rows, rcode;
   HSVTRIPLE hsvtab[256];
   cols = CALC_WIDTH(resimg);
   rows = CALC_HEIGHT(resimg);
   allocimage(&tmpres, cols, rows, 8);
   copyimage(srcimg, &tmpres);
   rgb2hsv(srcimg->palette, &hsvtab[0], srcimg->colors);
   qsort( (void *)hsvtab, tmpres.colors, sizeof(HSVTRIPLE), compare_hsv );
   hsv2rgb(&hsvtab[0], tmpres.palette, tmpres.colors);
   rcode = matchcolorimageex(srcimg, &tmpres, CR_TSDNODIFF);   
   rcode = copyimage(&tmpres, resimg);
   updatebitmapcolortable(resimg);
   freeimage(&tmpres);
   return(rcode);
}
int __cdecl compare_hsv(const void *hsv1, const void *hsv2)
{
   HSVTRIPLE *h1 = (HSVTRIPLE *)hsv1;
   HSVTRIPLE *h2 = (HSVTRIPLE *)hsv2;
   long val1, val2;
   int diff;
            // Sort palette by hue, saturation, value
   val1 = h1->hue * 256 * 256 + h1->saturation * 256 + h1->value;
   val2 = h2->hue * 256 * 256 + h2->saturation * 256 + h2->value;
   diff = (int)(val1 - val2);
   return(diff);
}

Copyright © 1997 Catenary Systems Inc. All rights reserved. Victor Image Processing Library is a trademark of Catenary Systems.


Victor Image Processing Library homepage | Victor Sample Code