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

colormapMATLAB

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?

Best Answer

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