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

# how to convert gray image to color image

Asked by Sivakumaran Chandrasekaran on 25 Aug 2012
```Image=imread('fog1.bmp');
[m n r]=size(Image)
rgb=zeros(m,n,3);
rgb(:,:,1)=Image;
rgb(:,:,2)=rgb(:,:,1);
rgb(:,:,3)=rgb(:,:,1);
Image=rgb/255;
figure,imshow(Image);
```

I am getting error in the line rgb(:,:,1)=Image;

Can anyone tell whats the error

Image Analyst on 25 Aug 2012

Siva, you've been asking enough questions here that you should learn how to format lines as code. Here's a tip: Just simply highlight the lines of code and click the {}Code icon above the text box. That will format it so that we will see it properly. I've done it for you this time but try to do it yourself next time - it's not hard. Thanks!

Thanks Image Analyst. I shall follow it

## Products

Answer by venkat vasu on 25 Aug 2012
Edited by Walter Roberson on 26 Aug 2012
```Image=imread('fog1.bmp');
if size(Image,3)==3
Image=rgb2gray(Image);
end
[m n r]=size(Image);
rgb=zeros(m,n,3);
rgb(:,:,1)=Image;
rgb(:,:,2)=rgb(:,:,1);
rgb(:,:,3)=rgb(:,:,1);
Image=rgb/255;
figure,imshow(Image);
```

Try this code...

## 1 Comment

Answer by Titus Edelhofer on 25 Aug 2012

Hi,

what's the value of r? One? Or three? I guess your Image is already an RGB image, only that R, G and B are always equal (and therefore you have gray) ...

Titus

Image Analyst on 25 Aug 2012

So the proper code would most likely be:

```rgbImage = imread('fog1.bmp');
[rows columns numberOfColorChannels] = size(rgbImage);
if numberOfColorChannels == 1
% It's monochrome, so convert to color.
rgbImage = cat(3, rgbImage, rgbImage, rgbImage);
end
imshow(rgbImage);
```

Thanks Image Analyst

Answer by Azzi Abdelmalek on 25 Aug 2012