How to display the intensity of 2D image as a colormap?

38 views (last 30 days)
I have a 2D image. and i want to plot a colormap that represents the intensity of each pixel as a color like the following picture:
I tried to use colormap(image) but it makes error " Error using colormap (line 98)
Colormap must have 3 columns: [R,G,B]."
Does anyone know how to do this in matlab?

Accepted Answer

Image Analyst
Image Analyst on 4 May 2020
Edited: Image Analyst on 4 May 2020
You need to pass in a colormap, N-by-3 array with values between 0 and 1, to to the colormap() function, NOT an image. And you should probably also pass in a handles to the axes you want to apply it to, otherwise it will apply that colormap to every axes in the figure window, which is probably not what you want. So in short, you want:
myColorMap = hsv(256); % Create a colormap.
colormap(gca, myColorMap); % Now apply the colormap.
You can also pass the colormap directly into imshow() and skip calling the colormap() function if you want.
See this full demo and study it:
grayImage = imread('cameraman.tif');
subplot(3, 1, 1);
imshow(grayImage);
axis('on', 'image');
title('Original Image');
subplot(3, 1, 2);
% Create a colormap.
myColorMap = hsv(256);
% Display image with that colormap.
imshow(grayImage, 'Colormap', myColorMap);
colorbar;
axis('on', 'image');
title('Overlay Image');
% Or equivalently, using the colormap() function:
subplot(3, 1, 3);
% Display image with no colormap.
imshow(grayImage);
% Create a colormap.
myColorMap = hsv(256);
% Now apply the colormap. Pass in the axes or else it will apply the colormap
% to ALL images on the figure, which is probably not what you want.
colormap(gca, myColorMap);
colorbar;
axis('on', 'image');
title('Overlay Image');
Now, if you already have a colormap, and you want to produce an RGB image, like to write to a file on disk rather than just pseudocoloring a displayed image, you want to call ind2rgb()
rgbImage = ind2rgb(grayImage, myColorMap);
  5 Comments
Image Analyst
Image Analyst on 5 May 2020
If your image values go from 0 to 1, it should already do that. Attach your code and image if you still need help.
ghada sandoub
ghada sandoub on 5 May 2020
I adjusted the color limits to be from 0 to 1 by using : CLim=[0 1] and it works well . Thank you so much.

Sign in to comment.

More Answers (1)

Ameer Hamza
Ameer Hamza on 4 May 2020
Edited: Ameer Hamza on 4 May 2020
Try this
im = im2double(imread('peacock.jpg'));
im_gray = rgb2gray(im);
pcolor(flipud(im_gray))
shading interp
colormap(jet)
colorbar
You can choose a different colormap from a list here: https://www.mathworks.com/help/releases/R2020a/matlab/ref/colormap.html#buc3wsn-1-map or create your own colormap as an mx3 matrix where each row is an RGB color.

Tags

Products

Community Treasure Hunt

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

Start Hunting!