This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Convert grayscale or binary image to indexed image


[X,cmap] = gray2ind(I,c)
[X,cmap] = gray2ind(BW,c)



[X,cmap] = gray2ind(I,c) converts the grayscale image I to an indexed image X with colormap cmap with c colors.

[X,cmap] = gray2ind(BW,c) converts the binary image BW to an indexed image.


collapse all

Read grayscale image into the workspace.

I = imread('cameraman.tif');

Convert the image to an indexed image using gray2ind. This example creates an indexed image with 16 indices.

[X, map] = gray2ind(I, 16);

Display the indexed image.

imshow(X, map);

Input Arguments

collapse all

Grayscale image, specified as a numeric array of any dimension.

Data Types: single | double | int16 | uint8 | uint16

Binary image, specified as a numeric array of any dimension.

Data Types: logical

Number of colormap colors, specified as a positive integer between 1 and 65536.

  • If the input image is grayscale, then the default value of c is 64.

  • If the input image is binary, then the default value of c is 2.

Output Arguments

collapse all

Indexed image, returned as a numeric array of the same dimensionality as the input grayscale or binary image. If the colormap length is less than or equal to 256, then the class of the output image is uint8 ; otherwise it is uint16.

Data Types: uint8 | uint16

Color map associated with indexed image X, returned as a c-by-3 numeric array. The color map produced is equivalent to gray(c).

Data Types: double

Introduced before R2006a