Clear Filters
Clear Filters

convert grayscale image into RGB

2 views (last 30 days)
vasantha malairamar
vasantha malairamar on 3 Apr 2017
Edited: DGM on 7 May 2023
im = imread('a.jpg');
rgb = ind2rgb(gray2ind(im,180),summer(100));
figure,imshow(rgb);

Answers (1)

DGM
DGM on 7 May 2023
Edited: DGM on 7 May 2023
OP's code example is remarkably correct, but for one likely problem. The likelihood of a JPG image being a single channel I image is small. The given code won't work if the input image is actually a grayscale RGB image.
While the simple solution would be to convert the incoming image to single-channel, I would like to take the opportunity to emphasize a minor point which may be of particular importance to readers. Contrary to OP's example and some of my own prior advice, if the goal is to emulate the behavior you might get from (for example) imagesc(), we shouldn't be using gray2ind().
Why not quantize the grayscale image using gray2ind()? The answer is simply that gray2ind() and image() (what underlies imshow() and imagesc()) do the quantizing differently. You could use gray2ind() if it's close enough for your tastes, but know that results will be different, especially if your color table is short.
For an example, I'm going to lean on some MIMT tools to do the job. Let's compare the results doing the quantization both ways.
% read an image (may be I/RGB)
inpict = imread('peppers.png');
% regardless of depth, convert it to a single channel image
% this converts the image to its BT601 luma component
% this is equivalent to im2gray(), but is not as version-dependent
% this is equivalent to rgb2gray() but is depth-agnostic and not IPT-dependent
inpict = mono(inpict,'y'); % BT601 luma
% get some desired color table
CT = ccmap(8);
% convert the image to pseudocolor
op1 = gray2pcolor(inpict,CT,'default'); % as gray2ind() quantizes
op2 = gray2pcolor(inpict,CT,'cdscale'); % as imagesc() quantizes
% concatenate outputs for easy viewing
outpict = [op1 op2];
imshow2(outpict)
The differences primarily are noticeable as the differing width of the extreme bins. Note the highlights on the yellow pepper and the shadows in the tablecloth. If your goal is to replicate the results you're seeing from imagesc() without relying on image capture, then you might want to take this difference into consideration.
The tools gray2pcolor() and the underlying uniquant() are currently unpublished parts of MIMT, though they will likely be published by the time anyone cares. Feel free to insist if your curiosity or need precede the consequence of my inertia.
See also:

Community Treasure Hunt

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

Start Hunting!