MATLAB Answers


gray image to rgb using ind2rgb

Asked by Elysi Cochin on 31 Aug 2013
Latest activity Edited by naushad waris
on 4 Jan 2017

please can someone show me how to convert a rgb image to gray and convert that gray image back to rgb using ind2rgb.... how to obtain map for the function ind2rgb..... Please do reply....


Log in to comment.

3 Answers

Answer by Walter Roberson
on 31 Aug 2013
 Accepted answer

You cannot convert grayscale images back to rgb without loss of information. Many different combinations of RGB values convert to the same grayscale level, so if all you have at a location is the grayscale level, then you cannot know which of the 65536 RGB values that map to the exact same grayscale that the RGB came from.

You can convert RGB to pseudocolor (ind). You could save a copy of the map used for that. You could convert each member of the pseudocolor map into grayscale and display it that way, and later you could convert back the pseudocolor map into RGB. However, if you want to do anything that modifies the grayscale (such as adaptive equalization) then you will have trouble.

[indimg, indmap] = rgb2ind(YourImage);
indasgray = rgb2gray(reshape(indmap,[size(indmap,1),1,3]));
colromap(indasgray);   %image painted gray but multiple ind might have same gray
ReconstructedImage = ind2rgb(indimg, indmap);   %not indasgray


sir then another error is

    ??? Error using ==> colormap at 89
    Colormap must have 3 columns: [R,G,B].
    Error in ==> Untitled3 at 8
    colormap(indasgray);   %image painted gray but multiple ind might have same gray

so what should i do to rectify it sir....

With rgb2ind() you don't pass in the number of colors in the input image, you pass in the number of colors you want in the indexed image. You may have a million colors in your input image (one unique color for every pixel) but if you're calling rgb2ind() then you're saying that you want an image with fewer colors in it, say 4 or 16, or 42 or 256 or whatever. How many did you specify or want? Show your code. Did you pass in all the required arguments? Is your image array really called YourImage? Is indasgray a 256 by 3 array?

colorMapSize = size(indasgray) % no semicolon
[indimg, indmap] = rgb2ind(YourImage, 256);
indasgray = rgb2gray(indmap;

Log in to comment.

Answer by Image Analyst
on 31 Aug 2013

Try this well-commented demo:

clc;    % Clear the command window.
close all;  % Close all figures (except those of imtool.)
clear;  % Erase all existing variables. Or clearvars if you want.
workspace;  % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 24;
% Read in a standard MATLAB color demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'peppers.png';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
	% Didn't find it there.  Check the search path for it.
	fullFileName = baseFileName; % No path this time.
	if ~exist(fullFileName, 'file')
		% Still didn't find it.  Alert user.
		errorMessage = sprintf('Error: %s does not exist.', fullFileName);
rgbImage = imread(fullFileName);
% Get the dimensions of the image.  numberOfColorBands should be = 3.
[rows, columns, numberOfColorBands] = size(rgbImage);
% Display the original color image.
subplot(1, 2, 1);
title('Original Color Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Ask user for a number.
defaultValue = 5;
titleBar = 'Enter a value';
userPrompt = 'Enter the number of colors: ';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
integerValue = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
    % They didn't enter a number.  
    % They clicked Cancel, or entered a character, symbols, or something else not allowed.
    integerValue = defaultValue;
    message = sprintf('I said it had to be an integer.\nI will use %d and continue.', integerValue);
% Call rgb2ind
[indexedImage, customizedColorMap] = rgb2ind(rgbImage, integerValue);
% Display it
subplot(1, 2, 2);
imshow(indexedImage, []);
caption = sprintf('Indexed image with %d colors', integerValue)
title(caption, 'FontSize', fontSize);


Log in to comment.

Answer by naushad waris
on 4 Jan 2017
Edited by naushad waris
on 4 Jan 2017

Please anyone provide the Tutorial or mathematical concept or background how they quantize the images usig three quantization techniques i.e. uniform quantization, minimum variance quantization, and colormap approximations. how we Can apply these quantization approaches to Intensity image or grayscale image alone.

RGB2IND Convert RGB image to indexed image. RGB2IND converts RGB images to indexed images using one of three different methods: uniform quantization, minimum variance quantization, and colormap approximation. RGB2IND dithers the image unless you specify 'nodither' for DITHER_OPTION.

   [X,MAP] = RGB2IND(RGB,N) converts the RGB image to an indexed image X
   using minimum variance quantization. MAP contains at most N colors.  N
   must be <= 65536.
   X = RGB2IND(RGB,MAP) converts the RGB image to an indexed image X with
   colormap MAP by matching colors in RGB with the nearest color in the
   colormap MAP.  SIZE(MAP,1) must be <= 65536.
   [X,MAP] = RGB2IND(RGB,TOL) converts the RGB image to an indexed image X
   using uniform quantization. MAP contains at most (FLOOR(1/TOL)+1)^3
   colors. TOL must be between 0.0 and 1.0.
   [...] = RGB2IND(...,DITHER_OPTION) enables or disables
   dithering. DITHER_OPTION is a string that can have one of these values:
       'dither'   dithers, if necessary, to achieve better color
                  resolution at the expense of spatial
                  resolution (default)
       'nodither' maps each color in the original image to the
                  closest color in the new map. No dithering is
   Class Support
   The input image can be of class uint8, uint16, or double. The output
   image is of class uint8 if the length of MAP is less than or equal to
   256, or uint16 otherwise.
       RGB = imread('flowers.tif');
       [X,map] = rgb2ind(RGB,128);


Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!