Convert from RGB to Grayscale without rgb2gray

조회 수: 43 (최근 30일)
Ray
Ray 2014년 10월 19일
댓글: DGM 2022년 4월 25일
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.

채택된 답변

Image Analyst
Image Analyst 2014년 10월 20일
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
thanh nguyen
thanh nguyen 2021년 10월 10일
i don't understand : "weighted sum" ? what is it? is it the fomula built-in?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Image Data Workflows에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by