Convert RGB image to indexed image
[X,map] = rgb2ind(RGB,n)
X = rgb2ind(RGB, map)
[X,map] = rgb2ind(RGB, tol)
[___] = rgb2ind(___,dither_option)
Dithers, if necessary, to achieve better color resolution at the expense of spatial resolution
Maps each color in the original image to the closest color in the new map. No dithering is performed.
The input image can be of class uint8, uint16, single, or double. If the length of map is less than or equal to 256, the output image is of class uint8. Otherwise, the output image is of class uint16.
The value 0 in the output array X corresponds to the first color in the colormap.
Read and display a truecolor uint8 JPEG image of a nebula.
RGB = imread('ngc6543a.jpg'); figure('Name','RGB Image') imagesc(RGB) axis image zoom(4)
Convert RGB to an indexed image with 32 colors
[IND,map] = rgb2ind(RGB,32); figure('Name','Indexed image with 32 Colors') imagesc(IND) colormap(map) axis image zoom(4)
If you specify tol, rgb2ind uses uniform quantization to convert the image. This method involves cutting the RGB color cube into smaller cubes of length tol.
If you specify n, rgb2ind uses minimum variance quantization. This method involves cutting the RGB color cube into smaller boxes (not necessarily cubes) of different sizes, depending on how the colors are distributed in the image. If the input image actually uses fewer colors than the number you specify, the output colormap is also smaller.
If you specify map, rgb2ind uses colormap mapping, which involves finding the colors in map that best match the colors in the RGB image.
Uniform Quantization — Uniform quantization cuts the RGB color cube into smaller cubes of length tol. For example, if you specify a tol of 0.1, the edges of the cubes are one-tenth the length of the RGB cube. The total number of small cubes is:
n = (floor(1/tol)+1)^3
Each cube represents a single color in the output image. Therefore, the maximum length of the colormap is n. rgb2ind removes any colors that don't appear in the input image, so the actual colormap can be much smaller than n.
Minimum Variance Quantization — Minimum variance quantization cuts the RGB color cube into smaller boxes (not necessarily cubes) of different sizes, depending on how the colors are distributed in the image. If the input image actually uses fewer colors than the number specified, the output colormap is also smaller.
Inverse Colormap — The inverse colormap algorithm quantizes the specified colormap into 32 distinct levels per color component. Then, for each pixel in the input image, the closest color in the quantized colormap is found.
 Spencer W. Thomas, "Efficient Inverse Color Map Computation", Graphics Gems II, (ed. James Arvo), Academic Press: Boston. 1991. (includes source code)