MATLAB Answers

How to apply a colormap to rgb image ?

5 views (last 30 days)
Mohamed Khaled
Mohamed Khaled on 14 Apr 2021
Commented: Adam Danz on 15 Apr 2021
I'm trying to assign a colormap (parula) to rgb image, I tried to convert the original image to gray scale then assigning the colormap (as shown in the mathworks tutorials [colormap(target,map)]) but there is an error that keeps appearing that I don't understand which is [Error using colormap (line 49)First argument must be a scalar axes or figure handle.]. Thanks in advance !
The Code:
I=imread('Capture3.PNG');
I_gray= im2gray(I);
IH_gray=imshow(I_gray)
colormap(I_gray,jet(256));

Accepted Answer

Adam Danz
Adam Danz on 14 Apr 2021
As the error message indicates, for the syntax colormap(target,map), target is an axis handle but you're not supplying an axis handle. You're supplying image data I.
IH_gray is the image object plotted to the current axes. Get the axis handle from that object's properties.
ax = ancestor(IH_gray,'axes'); % or ax = IH_gray.Parent;
colormap(ax,jet(256));
  2 Comments
Adam Danz
Adam Danz on 14 Apr 2021
IH_gray is an object handle.
The object is plotted on a pair of axes.
The first input to the colormap(target,map) specifyies what object the colormap should belong to. You are assigning the colormap to the axes so target should be the handle to the axes that contains the IH_gray object.
In other words, you want the axis handle that contains the image data. The image is a child of the axes and the axes are a parent of the image.
IH_gray.Parent is the axis handle.
Another way to the axis handle is with ancestor(IH_gray,'axes').
See also

Sign in to comment.

More Answers (2)

David Hill
David Hill on 14 Apr 2021
I=imread('Capture3.PNG');
I_gray= im2gray(I);
imshow(I_gray);
colormap('jet');

Image Analyst
Image Analyst on 15 Apr 2021
If you pass in the colormap arguments correctly without specifying an axes, it will use the last axes you displayed into.
rgbImage = imread('Capture3.PNG');
if ndims(rgbImage) == 3
I_gray = im2gray(rgbImage); % Only call this if you're 100% sure it's an RGB image.
end
imshow(I_gray)
colormap(jet(256));
Or you can pass the colormap directly into imshow():
rgbImage = imread('Capture3.PNG');
if ndims(rgbImage) == 3
I_gray = im2gray(rgbImage); % Only call this if you're 100% sure it's an RGB image.
end
imshow(I_gray, 'Colormap', (jet(256));
You actually passed in the thing IN the axes, not the aces handle itself.
  3 Comments
Adam Danz
Adam Danz on 15 Apr 2021
Right, or get the axis handle from the image object parent.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!