Eliminate duplicate colors in colormap; convert grayscale or truecolor image to indexed image
[Y,newmap] = cmunique(X,map)
[Y,newmap] = cmunique(RGB)
[Y,newmap] = cmunique(I)
[Y,newmap] = cmunique(X,map) returns the indexed image Y and associated colormap, newmap, that produce the same image as (X,map) but with the smallest possible colormap. The cmunique function removes duplicate rows from the colormap and adjusts the indices in the image matrix accordingly.
[Y,newmap] = cmunique(RGB) converts the truecolor image RGB to the indexed image Y and its associated colormap, newmap. The return value newmap is the smallest possible colormap for the image, containing one entry for each unique color in RGB.
Note: newmap might be very large, because the number of entries can be as many as the number of pixels in RGB.
[Y,newmap] = cmunique(I) converts the grayscale image I to an indexed image Y and its associated colormap, newmap. The return value, newmap, is the smallest possible colormap for the image, containing one entry for each unique intensity level in I.
The input image can be of class uint8, uint16, or double. The class of the output image Y is uint8 if the length of newmap is less than or equal to 256. If the length of newmap is greater than 256, Y is of class double.
Use the magic function to create a sample 4-by-4 image that uses every value in the range between 1 and 16.
X = magic(4) X = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
Concatenate two 8-entry grayscale colormaps created using the gray function. The resultant colormap, map, has 16 entries. Entries 9 through 16 are duplicates of entries 1 through 8.
map = [gray(8); gray(8)] size(map) ans = 16 3
Use cmunique to eliminate duplicate entries in the colormap.
[Y, newmap] = cmunique(X, map); size(newmap) ans = 8 3
cmunique adjusts the values in the original image X to index the new colormap.
Y = 7 1 2 4 4 2 1 7 0 6 5 3 3 5 6 0
View both images to verify that their appearance is the same.
figure, imshow(X, map, 'InitialMagnification', 'fit') figure, imshow(Y, newmap, 'InitialMagnification', 'fit')