MATLAB Answers

How to create an RGB image?

508 views (last 30 days)
Zeff020 on 26 May 2017
Answered: Tariq Hussain on 25 Jun 2019
What I have done thus far to create RGB images is to just load a white image and seperate the red green and blue components from this image and combine them in different ways to get different colors. No this feels kind of redundant because I keep thinking that MatLab must have a built-in RGB system in which you can just write a one line code from which the output will be any of the colors within RGB. Is there a simple function for this?

  1 Comment

Walter Roberson
Walter Roberson on 26 May 2017
I am not clear as to what the desired inputs would be, or the desired outputs?

Sign in to comment.

Answers (3)

MathReallyWorks on 26 May 2017
Edited: MathReallyWorks on 26 May 2017
As far as I know, there is no direct function to do this. But if you want you can create a user defined function to randomly select any of the colors within RGB.
If you want to create RGB image from some kind of matrix, try this:
image=zeros(300,400,3); %initialize
image(:,1:100,1)=0.5; %Red (dark red)
image(:,101:200,1)=1; %Red (maximum value)
image(1:100,:,2)=rand(100,400); %Green
figure, imshow(image)


Sign in to comment.

Jan on 26 May 2017
No, there is no such command. Accessing the channels is so easy, that it is not worth to create a dedicated function:
RGB = rand(64, 48, 3); % RGB Image
R = RGB(:, :, 1);
G = RGB(:, :, 2);
B = RGB(:, :, 3);
IMG1 = cat(3, G, R, B);
Now the channels swapped.


Zeff020 on 26 May 2017
Ok, thanks! this is basically what I did. The problem that I had with this though is that you can only create the primary colors RGB and (when you combine these) their secondary colors: Yellow, Magenta and Turquoise. Now I would like to be able to create every color on the spectrum, is there no function to do this?
Jan on 26 May 2017
Do you mean:
IMG1 = cat(3, 0.8*G + 0.2*R, 0.3*R + 0.7*B, 0.1*B + 0.2*G + 0.7*R);
Of course you can get the full RGB spektrum.
What exactly is the problem you want to solve? Which color should be produced based on which input?
Walter Roberson
Walter Roberson on 26 May 2017
Looking at perhaps the request is for the ability to input a color name and get an rgb value out.
Or perhaps the request is just for something like
swath = @(r,g,b,rows,cols) = cat(3, r * ones(rows, cols), g * ones(rows, cols), b * ones(rows, cols) )
or equivalently
swath = @(r,g,b,rows,cols) = repmat( cat(3,r,g,b), rows, cols, 1)
Either of these would produce a rows x cols matrix of solid color with components r, g, and b.

Sign in to comment.

Tariq Hussain
Tariq Hussain on 25 Jun 2019


Sign in to comment.


Community Treasure Hunt

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

Start Hunting!

Translated by