Setting RGB image CData to greyscale image colourmap wrong

4 views (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 3 Jun 2016
Edited: Walter Roberson on 3 Jun 2016
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.
  2 Comments
Callum Clarke
Callum Clarke on 3 Jun 2016
These images are uint8 so this line worked on it's own, thanks! Out of interest, how could this deal with cases where the image bit depth is different? I couldn't find a way to get the bit depth of an image last time I looked.
Walter Roberson
Walter Roberson on 3 Jun 2016
imfinfo(filename) and look at the BitDepth property. BitDepth is something stored with image files, not with arrays. With arrays the most you can ask is class() which can tell you uint8, uint16, but cannot tell you how many of those 8 or 16 bits are actually used.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!