Honeybear
Honeybear

Reputation: 3138

Convert matlab.graphics.primitive.Image (output of imagesc) to rgb array

I'm using the MATLAB function

imagesc(my_gray_valued_image)

to visualize my_gray_valued_image: [1024x1024] double array with values from 0.0 - 1.0 (gray values) using colormaps like jet.

I want to store the output as a RGB image ([1024x1024x3] double array). However the output of the function is a Image object (matlab.graphics.primitive.Image) that contains the original array (Image.CData) but doesn't allow to extract the colorscaled image.

Following a similar (although confusingly cluttered) question (How to convert an indexed image to rgb image in MATLAB?) I tried the following, but that gave me a plain blue image:

RGB = ind2rgb(my_gray_valued_image, jet);
imshow(RGB);

Upvotes: 2

Views: 4886

Answers (2)

user2999345
user2999345

Reputation: 4195

here for arbitrary colormap:

im = rand(5); % input [0-1] image
figure;
h = imagesc(im); % imagesc handle
title('imagesc output')
cdata = h.CData; % get image data (if you don't have variable 'im')
cm = colormap(h.Parent); % get axes colormap
n = size(cm,1); % number of colors in colormap
c = linspace(h.Parent.CLim(1),h.Parent.CLim(2),n); % intensity range
ind = reshape(interp1(c,1:n,im(:),'nearest'),size(im)); % indexed image
rgb = ind2rgb(ind,cm); % rgb image
figure;
imshow(rgb,'InitialMagnification','fit');
title('rgb image')

enter image description here

enter image description here

Upvotes: 3

Luis Mendo
Luis Mendo

Reputation: 112699

You can use ind2rgb to convert an intensity image into RGB using a colormap of your choice; but make sure that the range of the input is from 1 to the number of colors in the colormap. This is because ind2rgb maps value 1 to the first color, 2 to the second etc.

im = rand(5,5); % example intensity image
cmap = jet(256); % desired colormap
result = ind2rgb(ceil(size(cmap,1)*im), cmap);

The reason why you are getting a blue image is that ind2rgb clips the values of the input image to the range from 1 to the number of colors in the colormap. So, if the input image has values between 0 and 1 they are all mapped to 1, that is, to the first color in the colormap.

Upvotes: 1

Related Questions