# Converting grayscale image to indexed

6 views (last 30 days)
Micha on 19 Aug 2018
Answered: Micha on 19 Aug 2018
I have a grayscale image with 3 random values signified by integers 91, 123, 255. When I use gray2ind(I, 3) I get only 2 indices: 1 and 2. But when I use gray2ind(I, 2) I get 0 and 1 as expected. How come? I would expect gray2ind(I, 3) to give me 0, 1 and 2.
I do have a colormap array which I am planning to later use, which has 3 individual colors, such that after I would properly convert this to 0, 1 and 2 indices I'd just do imshow(gray2ind(I, 3), colors).
Thanks

Image Analyst on 19 Aug 2018
Don't worry about it. You can use a grayscale image as an indexed image as-is. Just set up the colormap based on the grayscale and set the map for whatever colors you want for the special values.
% Initialize a normal colormap for a normal gray scale image.
cmap = gray(256);
% Set up special colors for 91, 123, 255.
cmap(92, :) = [1, 1, 0]; % Gray scale 91 will show up as yellow.
cmap(124, :) = [1, 0, 1]; % Gray scale 123 will show up as magenta.
cmap(256, :) = [1, 0, 0]; % Gray scale 255 will show up as red.
imshow(grayImage, cmap);
colorbar
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
However, note that the index (row) of the colormap you want to use is one more than the gray level, because row 1 controls the color of gray level 0, row 2 controls the color of gray level 1, and so on until row 256 controls the color of gray level 255.
Image Analyst on 19 Aug 2018
Try this:
% Quantize into 3 gray levels.
qImage = imquantize(grayImage, [91, 123, 255]);
unique(qImage)
% Set up a color map for color 1 valid for GL <=91,
% color 2 valid for GL >= 92 up to GL <= 123,
% and color 3 valid for GL >= 124 up to GL <= 255.
cmap = [1, 1, 0;
1, 0, 1;
1, 0, 0];
imshow(qImage, cmap);
colorbar
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);

Micha on 19 Aug 2018
Thanks, imquantize was what I was looking for.

### Categories

Find more on Colormaps in Help Center and File Exchange

R2017a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!