Convert from RGB to Grayscale without rgb2gray

13 views (last 30 days)
Basically, I need to make a function [gray] = grayscale(color) without using rgb2gray. Basically, I am taking in a 3x3 matrix with color and returning a 2x2 matrix with gray. I get the fact that I have to extract the red, green and blue channels using:
redChannel = color(:, :, 1);
greenChannel = color(:, :, 2);
blueChannel = color(:, :, 3);
and then using the weighted average:
gray = .299*redChannel + .587*greenChannel + .114*blueChannel
but I do not know how to make that gray into a 2x2 matrix. Any help is appreciated.

Accepted Answer

Image Analyst
Image Analyst on 20 Oct 2014
Your 3x3 and 2x2 jargon is all messed up so I will ignore it. You're almost there with your function though. First I wouldn't use color as the name of a variable since it's so often the name of a parameter. So let's call it rgbImage. So your function is
function grayImage = grayscale(rgbImage)
try
[rows, columns, numberOfColorChannels = size(rgbImage);
if numberOfColorChannels == 3
% It's color, need to convert it to grayscale.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Do the weighted sum.
grayImage = .299*double(redChannel) + ...
.587*double(greenChannel) + ...
.114*double(blueChannel);
% You probably want to convert it back to uint8 so you can display it.
grayImage = uint8(grayImage);
else
% It's already gray scale.
grayImage = rgbImage; % Input image is not really RGB color.
end
catch ME
errorMessage = sprintf('Error in function %s() at line %d.\n\nError Message:\n%s', ...
ME.stack(1).name, ME.stack(1).line, ME.message);
fprintf(1, '%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
This will take a rows-by-columns-by-3 image (a 3-D image) and convert it to a rows-by-columns image (a 2-D image). You could make it a little more robust by checking that numberOfColor channels is either 1 or 3 and throw an error if it's not, but that likely won't happen if you pass it what you're supposed to.
  6 Comments
thanh nguyen
thanh nguyen on 10 Oct 2021
i don't understand : "weighted sum" ? what is it? is it the fomula built-in?

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!