Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

convert matrix to rgb

Asked by Philipp on 6 Aug 2012
Latest activity Commented on by Bruno on 31 Jan 2014

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

0 Comments

Philipp

Tags

Products

No products are associated with this question.

4 Answers

Answer by Matt Fig on 6 Aug 2012
Accepted answer

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)?
subplot(1,2,1)
imagesc(G);
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.
subplot(1,2,2)
image(H)  % Does this image match the other one?
title('IMAGE (MxNx3)')

3 Comments

Philipp on 8 Aug 2012

Hi Matt, thanks for you helpful answer, it really addresses the problem I was struggling with. I found it also to be useful to create the lookup table directly from jet(1:1000) without the need of an interpolation.

br philipp

Seth on 1 May 2013

This is very helpful Matt - solved my problem as well - very efficiently I might add.

The only thing I would add is that if you don't want to display a figure during this process (just work with data), then you need to modify the following lines:

Change: C = colormap; % Get the figure's colormap.

To: C = jet(64); %State the name of the colormap and the number of levels

For whatever reason, the function "colormap" creates and displays an empty window where as directly defining the colormap by name and number of levels suppresses the creation of a new figure.

Thanks again for the great piece of code.

Bruno on 31 Jan 2014

Such beatiful peace of code. I'm very thankful!

Matt Fig
Answer by 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.

0 Comments

Image Analyst
Answer by Jurgen on 1 May 2013

The FEX has mat2im and real2rgb. Can recommend both!

real2rgb

mat2im

double2rgb

1 Comment

Jurgen on 1 May 2013

Just noticed this thread was old...

Jurgen

Contact us