MATLAB Answers

convert matrix to rgb

324 views (last 30 days)
Philipp on 6 Aug 2012
Commented: Mathieu on 12 Aug 2015
dear matlab developers,
i have a double matrix (MxN). is there a way to convert it to RGB?
when i use imagesc(matrix), all the values are color coded and displayed, but is there a way to write the RGB values into a new array (MxNx3)?
br philipp

Accepted Answer

Matt Fig
Matt Fig on 6 Aug 2012
I wonder if this is what you mean, Philipp?
% Say this is the given matrix:
G = rand(10,10)*300 - 100;
% Use IMAGESC to plot G.
figure('pos',[100 100 1000 800]);
% colormap(copper) % You realize this affects final image (H)?
title('IMAGESC (MxN)')
% Now make an RGB image that matches display from IMAGESC:
C = colormap; % Get the figure's colormap.
L = size(C,1);
% Scale the matrix to the range of the map.
Gs = round(interp1(linspace(min(G(:)),max(G(:)),L),1:L,G));
H = reshape(C(Gs,:),[size(Gs) 3]); % Make RGB image from scaled.
image(H) % Does this image match the other one?
title('IMAGE (MxNx3)')
Mathieu on 12 Aug 2015
Thank you so Much Matt, very helpful!!

Sign in to comment.

More Answers (3)

Jurgen on 1 May 2013
The FEX has mat2im and real2rgb. Can recommend both!
  1 Comment
Jurgen on 1 May 2013
Just noticed this thread was old...

Sign in to comment.

Image Analyst
Image Analyst on 6 Aug 2012
rgbImage = cat(3, redChannel, greenChannel, blueChannel);
Cast to uint8 if you want to display or save to a file. Scale to 0-255 if it's not already in that range. mat2gray() might help.


Community Treasure Hunt

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

Start Hunting!