9 Convert a colour to a grayscale value

The images captured by the webcam are colour images. Every pixel in a colour image is represented by 3 values: R, G, and B where: - R represents the amount of red light that is in the color - G represents the amount of green light that is in the colour, and - B represents the amount of blue light that is in the colour

In MATLAB, the values of R, G, and B usually lie in the range of 0 to 255 (but the range 0 to 1 is also commonly used).

For our simple target tracking problem it is much easier to work with grayscale images. Given the three colour values R, G, and B we can compute the corresponding gray value Y as:

\[ Y = 0.2989R + 0.5870G + 0.1140B \]

9.1 Write a function to convert a colour to a grayscale value

In MATLAB, create and complete the following function:

function gray = toGray(red, green, blue) 
%TOGRAY Convert RGB to grayscale.
%   gray = toGray(red, green, blue) converts the vectors of
%   color values red, green, and blue to grayscale.
%   For each value red(i), green(i), blue(i) the corresponding
%   grayscale value is computed as:
%
%   gray(i) = 0.2989 * red(i) + 0.5870 * green(i) + 0.1140 * blue(i)
%
%   The returned vector gray is the same size as red, green, and blue.

You should pre-allocate the result vector gray first (like we did in the script labF) and then use a loop to compute the values of gray(i).

9.2 Test your function

Test your function by converting and displaying your captured colour image to grayscale by typing the following into the Command Window:

[rows, cols, layers] = size(colimg);
y = zeros(rows, cols);
for i = 1:rows
    % converts each row of img to grayscale
    y(i, :) = toGray(colimg(i, :, 1), colimg(i, :, 2), colimg(i, :, 3));
end
% convert y from double to an integer value between 0 and 255
y = uint8(y);
% show the grayscale image y
imshow(y)

My colour image converted to grayscale looks like:

When you think that your function is working correctly, convert your captured image of the target to grayscale (it already looks like it is a grayscale image, but its actual representation is a colour image) by typing the following into the Command Window:

[rows, cols, layers] = size(img);
gray = zeros(rows, cols);
for i = 1:rows
    % converts each row of img to grayscale
    gray(i, :) = toGray(img(i, :, 1), img(i, :, 2), img(i, :, 3));
end
% convert y from double to an integer value between 0 and 255
gray = uint8(gray);
% show the grayscale image y
imshow(gray)