# MATLAB | RGB image to grayscale image conversion

• Difficulty Level : Easy
• Last Updated : 25 Jun, 2018

An RGB image can be viewed as three images( a red scale image, a green scale image and a blue scale image) stacked on top of each other. In MATLAB, an RGB image is basically a M*N*3 array of colour pixel, where each colour pixel is a triplet which corresponds to red, blue and green colour component of RGB image at a specified spatial location.

Similarly, A Grayscale image can be viewed as a single layered image. In MATLAB, a grayscale image is basically M*N array whose values have been scaled to represent intensities.

In MATLAB, there is a function called rgb2gray() is available to convert RGB image to grayscale image. Here we will convert an RGB image to grayscale image without using rgb2gray() function.

Our key idea is to convert an RGB image pixel which a triplet value corresponding to red, blue and green colour component of an image at a specified spatial location to a single value by calculating a weighted sum of all three colour component.

Algorithm for conversion:

1. Read RGB colour image into MATLAB environment
2. Extract Red, blue and green colour components from RGB image into 3 different 2-D matrices
3. Create a new matrix with the same number of rows and columns as RGB image, containing all zeros .
4. Convert each RGB pixel values at location (i, j) to grayscale values by forming a weighted sum of the Red, Green, and Blue colour components and assign it to corresponding location (i, j) in new matrix
5. ``grayscale value at (i, j) = 0.2989 * R(i, j) + 0.5870 * G(i, j) + 0.1140 * B(i, j);``

Note: The coefficients that is used to calculate grayscale values are identical to those that is used to calculate luminance (E’y) in Rec. ITU-R BT.601-7 (Recommendation by radio-communication sector of ITU for Broadcasting service (Television))

Implementation:

```% Function will take a colour image as input  and will return a grayscale image
function [gray_img] = colouredToGray(img)
% Extract Red colour component to R, Green colour component to G
% and Blue colour component to  B
R=img(:, :, 1);
G=img(:, :, 2);
B=img(:, :, 3);

% Getting number of rows in M and number of column in N of RGB image matrix
% ~ is used to ignore dimension of RGB image
% as size(img) function will return row, column and dimension of the RGB image
[M, N, ~]=size(img);

% creating a new 2-d matrix 'gray_img' of size M*N of 'uint8' data type with all
% elements  as zero
gray_img=zeros(M, N, 'uint8');

% calculating grayscale values by forming a weighted sum of the R, G, and B components
% for each pixel
for i=1:M
for j=1:N
gray_img(i, j)=(R(i, j)*0.2989)+(G(i, j)*0.5870)+(B(i, j)*0.114);
end
end
end
```

The above function will be called from MATLAB command window

```>> % Reading  an RGB image file in MATLAB environment

>> % The above function will be called here
>> I=colouredToGray(img);
>> figure, imshow(I);
```

Input: Output: 