How can I retrieve RGB array from a colormap given a CData?

Hello,
If I have a designated colormap, jet for example, and the caxis is set to [0 1] and I want to return the RGB values (array of three numbers) of CData 0.5, how can I do this?
Thanks!

 Accepted Answer

Isn't it just half way up your colormap? So if you specify 256 colors
cmap = jet(256);
and the first row cmap(1,:) applies to 0, and the last row cmap(256,:) applied to values of 1, then 0.5 will be the middle row of your colormap (green if you chose jet). See:
grayImage = imread('moon.tif');
grayImage = im2double(grayImage);
imshow(grayImage);
cmap = jet(256);
colormap(gca, cmap);
colorbar;
% Find the middle row, which corresponds to an image value of 0.5
middleRow = round(size(cmap, 1) / 2)
% Print the color there out to the command window:
cmap(middleRow, :)
% Shows ans = 0.5 1 0.5 (green color as expected);

3 Comments

This was exactly what I needed! Thank you.
You're welcome. If we're done then, could you "Accept this Answer"? Thanks in advance.
Hi Image Analyst, you've helped me in several ocassions, I really think you are very good on these topics, I would like you kindly request you to check this question if it is ok for you:https://www.mathworks.com/matlabcentral/answers/487875-how-to-set-a-colorbar-using-specific-rgb-values-and-limit-values .. Thanks in advance

Sign in to comment.

More Answers (1)

By default (with CDataMapping property is set to 'scale'), CData is scaled to "map" to colormap range. So if you somehow convert the CData, colormap to index image, you can then convert indexed image to RGB image using ind2rgb function. The example follows.
% Example plot with colormap
h = surf(peaks);
Cdata = h.CData;
cmap = colormap;
% make it into a index image.
cmin = min(Cdata(:));
cmax = max(Cdata(:));
m = length(cmap);
index = fix((Cdata-cmin)/(cmax-cmin)*m)+1; %A
% Then to RGB
RGB = ind2rgb(index,cmap)
Please note that if you specify index as an array of class single or double, then the value 1 corresponds to the first color in the colormap (see +1 at %A above).
Related doc pages:

1 Comment

Or on the last step instead of ind2rgb, just
RGB = cmap(index,:)
It depends whether you want something x 3 (my version) or something by something x 3 (Michio's code)

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!