rgb2ind

Converts an RGB image to an indexed image using a given colormap.

Category: Graphics > Images

Syntax

X = rgb2ind(RGB, map)

Maps each pixel to the index of the nearest color in map.

[X, map] = rgb2ind(RGB, n)

Quantizes the image to at most n colors and returns the new colormap.

Description

Indexed images store one small integer per pixel plus a palette, so they take less memory when few colors are needed. Matching to a fixed palette picks the closest color by distance in RGB space; dither can be used instead to disguise the loss with patterns.

Input arguments

RGB
Truecolor image.
map
Colormap to match against.
n
Number of colors to use when the colormap is computed.

Output arguments

X
Indexed image. Its class is uint8 for up to 256 colors, otherwise uint16; indices start at 0.
map
The colormap used.

Example

Match a two-color palette

RGB = zeros(1, 2, 3);
RGB(1, 1, :) = [1 0 0];
RGB(1, 2, :) = [0 1 0];
X = rgb2ind(RGB, [1 0 0; 0 1 0])
class(X)
Output
X = 1×2 uint8 row vector

   0   1
ans = 'uint8'

Notes

In MatLivre a colormap must be supplied; automatic quantization to a number of colors is not supported.

See also

ind2rgb dither cmunique rgb2gray