ImageMagick – MagickCore, C API: Reduce the Number of Unique Colors in an Image
Author: ImageMagick Studio LLC
Description: ImageMagick is a powerful, open-source software suite for creating, editing, converting, and manipulating images in over 200 formats. Ideal for web developers, graphic designers, and researchers, it offers versatile tools for image processing, including batch processing, format conversion, and complex image transformations.
Keywords: MagickCore, C API: Reduce the Number of Unique Colors in an Image, Image Processing, Digital Image Editing, Image Conversion, Open-Source Software, Image Manipulation, Command-Line Image Tools

# Quantize

## QuantizeImage

QuantizeImage() takes a standard RGB or monochrome images and quantizes them down to some fixed number of colors.

For purposes of color allocation, an image is a set of n pixels, where each pixel is a point in RGB space. RGB space is a 3-dimensional vector space, and each pixel, Pi, is defined by an ordered triple of red, green, and blue coordinates, (Ri, Gi, Bi).

Each primary color component (red, green, or blue) represents an intensity which varies linearly from 0 to a maximum value, Cmax, which corresponds to full saturation of that color. Color allocation is defined over a domain consisting of the cube in RGB space with opposite vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax = 255.

The algorithm maps this domain onto a tree in which each node represents a cube within that domain. In the following discussion these cubes are defined by the coordinate of two opposite vertices (vertex nearest the origin in RGB space and the vertex farthest from the origin).

The tree's root node represents the entire domain, (0,0,0) through (Cmax,Cmax,Cmax). Each lower level in the tree is generated by subdividing one node's cube into eight smaller cubes of equal size. This corresponds to bisecting the parent cube with planes passing through the midpoints of each edge.

The basic algorithm operates in three phases: Classification, Reduction, and Assignment. Classification builds a color description tree for the image. Reduction collapses the tree until the number it represents, at most, the number of colors desired in the output image. Assignment defines the output image's color map and sets each pixel's color by restorage_class in the reduced tree. Our goal is to minimize the numerical discrepancies between the original colors and quantized colors (quantization error).

Classification begins by initializing a color description tree of sufficient depth to represent each possible input color in a leaf. However, it is impractical to generate a fully-formed color description tree in the storage_class phase for realistic values of Cmax. If colors components in the input image are quantized to k-bit precision, so that Cmax= 2k-1, the tree would need k levels below the root node to allow representing each possible input color in a leaf. This becomes prohibitive because the tree's total number of nodes is 1 + sum(i=1, k, 8k).

A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.

avoid building a fully populated tree, QUANTIZE

(1) Initializes data structures for nodes only as they are needed; (2) Chooses a maximum depth for the tree as a function of the desired number of colors in the output image (currently log2(colormap size)).

For each pixel in the input image, storage_class scans downward from the root of the color description tree. At each level of the tree it identifies the single node which represents a cube in RGB space containing the pixel's color. It updates the following data for each such node:

        n1: Number of pixels whose color is contained in the RGB cube which
        this node represents;

n2: Number of pixels whose color is not represented in a node at lower depth in the tree; initially, n2 = 0 for all nodes except leaves of the tree.

Sr, Sg, Sb: Sums of the red, green, and blue component values for all pixels not classified at a lower depth. The combination of these sums and n2 will ultimately characterize the mean color of a set of pixels represented by this node.

E: the distance squared in RGB space between each pixel contained within a node and the nodes' center. This represents the quantization error for a node.

Reduction repeatedly prunes the tree until the number of nodes with n2 > 0 is less than or equal to the maximum number of colors allowed in the output image. On any given iteration over the tree, it selects those nodes whose E count is minimal for pruning and merges their color statistics upward. It uses a pruning threshold, Ep, to govern node selection as follows:

  Ep = 0 while number of nodes with (n2 > 0) > required maximum number of colors prune all nodes such that E <= Ep Set Ep to minimum E in remaining nodes
  This has the effect of minimizing any quantization error when merging two nodes together.
  When a node to be pruned has offspring, the pruning procedure invokes itself recursively in order to prune the tree from the leaves upward. n2, Sr, Sg, and Sb in a node being pruned are always added to the corresponding data in that node's parent. This retains the pruned node's color characteristics for later averaging.
  For each node, n2 pixels exist for which that node represents the smallest volume in RGB space containing those pixel's colors. When n2 > 0 the node will uniquely define a color in the output image. At the beginning of reduction, n2 = 0 for all nodes except a the leaves of the tree which represent colors present in the input image.
  The other pixel count, n1, indicates the total number of colors within the cubic volume which the node represents. This includes n1 - n2 pixels whose colors should be defined by nodes at a lower level in the tree.
  Assignment generates the output image from the pruned tree. The output

parts
  (1) A color map, which is an array of color descriptions (RGB triples) for each color present in the output image; (2) A pixel array, which represents each pixel as an index into the color map array.
  First, the assignment phase makes one pass over the pruned color description tree to establish the image's color map. For each node with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean color of all pixels that classify no lower than this node. Each of these colors becomes an entry in the color map.
  Finally, the assignment phase reclassifies each pixel in the pruned tree to identify the deepest node containing the pixel's color. The pixel's value in the pixel array becomes the index of this node's mean color in the color map.
  This method is based on a similar algorithm written by Paul Raveling.

## AcquireQuantizeInfo

AcquireQuantizeInfo() allocates the QuantizeInfo structure.

The format of the AcquireQuantizeInfo method is:

    QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)

A description of each parameter follows:

image_info
  the image info.

## CloneQuantizeInfo

CloneQuantizeInfo() makes a duplicate of the given quantize info structure, or if quantize info is NULL, a new one.

The format of the CloneQuantizeInfo method is:

    QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)

A description of each parameter follows:

clone_info
  Method CloneQuantizeInfo returns a duplicate of the given quantize info, or if image info is NULL a new one.
quantize_info
  a structure of type info.

## CompressImageColormap

CompressImageColormap() compresses an image colormap by removing any duplicate or unused color entries.

The format of the CompressImageColormap method is:

    MagickBooleanType CompressImageColormap(Image *image)

A description of each parameter follows:

image
  the image.

## DestroyQuantizeInfo

DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo structure.

The format of the DestroyQuantizeInfo method is:

    QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)

A description of each parameter follows:

quantize_info
  Specifies a pointer to an QuantizeInfo structure.

## GetImageQuantizeError

GetImageQuantizeError() measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value. These values are computed:

        o mean_error_per_pixel:  This value is the mean error for any single
    pixel in the image.

normalized_mean_square_error

This value is the normalized mean quantization error for any single pixel in the image. This distance measure is normalized to a range between 0 and 1. It is independent of the range of red, green, and blue values in the image.

normalized_maximum_square_error

This value is the normalized maximum quantization error for any single pixel in the image. This distance measure is normalized to a range between 0 and 1. It is independent of the range of red, green, and blue values in your image.

The format of the GetImageQuantizeError method is:

    MagickBooleanType GetImageQuantizeError(Image *image)

A description of each parameter follows.

image

the image.

## GetQuantizeInfo

GetQuantizeInfo() initializes the QuantizeInfo structure.

The format of the GetQuantizeInfo method is:

    GetQuantizeInfo(QuantizeInfo *quantize_info)

A description of each parameter follows:

quantize_info
  Specifies a pointer to a QuantizeInfo structure.

## PosterizeImage

PosterizeImage() reduces the image to a limited number of colors for a "poster" effect.

The format of the PosterizeImage method is:

    MagickBooleanType PosterizeImage(Image *image,const size_t levels,
      const MagickBooleanType dither)
    MagickBooleanType PosterizeImageChannel(Image *image,
      const ChannelType channel,const size_t levels,
      const MagickBooleanType dither)

A description of each parameter follows:

image
  Specifies a pointer to an Image structure.
levels
  Number of color levels allowed in each channel. Very low values (2, 3, or 4) have the most visible effect.
dither
  Set this integer value to something other than zero to dither the mapped image.

## QuantizeImage

QuantizeImage() analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

The format of the QuantizeImage method is:

    MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
      Image *image)

A description of each parameter follows:

quantize_info
  Specifies a pointer to an QuantizeInfo structure.
image
  the image.

## QuantizeImages

QuantizeImages() analyzes the colors within a set of reference images and chooses a fixed number of colors to represent the set. The goal of the algorithm is to minimize the color difference between the input and output images while minimizing the processing time.

The format of the QuantizeImages method is:

    MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
      Image *images)

A description of each parameter follows:

quantize_info
  Specifies a pointer to an QuantizeInfo structure.
images
  Specifies a pointer to a list of Image structures.

## RemapImage

RemapImage() replaces the colors of an image with the closest color from a reference image.

The format of the RemapImage method is:

    MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
      Image *image,const Image *remap_image)

A description of each parameter follows:

quantize_info
  Specifies a pointer to an QuantizeInfo structure.
image
  the image.
remap_image
  the reference image.

## RemapImages

RemapImages() replaces the colors of a sequence of images with the closest color from a reference image.

The format of the RemapImage method is:

    MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
      Image *images,Image *remap_image)

A description of each parameter follows:

quantize_info
  Specifies a pointer to an QuantizeInfo structure.
images
  the image sequence.
remap_image
  the reference image.

## SetGrayscaleImage

SetGrayscaleImage() converts an image to a PseudoClass grayscale image.

The format of the SetGrayscaleImage method is:

    MagickBooleanType SetGrayscaleImage(Image *image)

A description of each parameter follows:

image
  The image.