MATLAB Answers


gray image to rgb using ind2rgb

Asked by Elysi Cochin on 31 Aug 2013

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....


2 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;

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);


Join the 15-year community celebration.

Play games and win prizes!

Learn more
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!