MATLAB: Setting RGB image CData to greyscale image colourmap wrong

colormapimage processingImage Processing ToolboxMATLAB

Changing the CData on an RGB image to a greyscale image causes incorrect colours (shades of red). I'm assuming it's something to do with the colormap. Pseudocode of what I'm trying:
handle = imshow(RBGImage); % Shows up fine
greyscaleImage = rgb2gray(RGBImage);
set(handles, 'CData', greyscaleImage); % Produces 'redscale' image
If I do it the other way round, replacing greyscale with RGB, it works fine.
I have tried colormap(fig, 'gray') but this produces a solid grey image during normal execution. Strangely if I step through the code it instead produces a greyscale image of the wrong hue. Just using imshow(greyscaleImage) works fine but I'm trying to prevent repeated imshow calls.

Best Answer

colormap(YourAxes, gray(256))
The step after that will depend upon whether the data is in the range 0 to 1 or if it is uint8 0 to 255. You might have to change the CDataMapping property of the image, and you might have to change the axes CLim property.
I changed fig to YourAxes to reflect that fact that formally speaking, colormap has long been defined to take an axes rather than a figure. Up to R2014a there was only one colormap per figure, but from R2014b onwards there is one colormap per axes.
Related Question