Change RGB image to gray without rgb2gray function

82 views (last 30 days)
David Chiu
David Chiu on 31 Oct 2020
Answered: DGM on 25 Apr 2022
Load a RGB Image and convert to grayscale as shown in the following example.
Hint:
0.2989 * R + 0.5870 * G + 0.1140 * B
Reference function rgb2gray( ) in MATLAB
Hint:
Convert uint8 to double datatype before you process the image.
Normalize the final image matrix and convert back to
uint8 before you show the image.

Answers (3)

Ameer Hamza
Ameer Hamza on 31 Oct 2020
Edited: Ameer Hamza on 31 Oct 2020
Since this is a homework question so I won't give the complete answer, but, you can use the following hints from following code.
Seperate channels in the image
img; % RGB image
img = im2double(img); % convert image to double datatype
r = img(:,:,1);
g = img(:,:,2);
b = img(:,:,3);
r, g, and b are 2D matrices. You can do their weighted sum using formula in your question and you will get the grayscale image. Finally convert the grayscale image back to uint8 format
gray_image; % image you get after adding three channles
gray_image = im2uint8(gray_image)
  4 Comments

Sign in to comment.


Image Analyst
Image Analyst on 31 Oct 2020
When they say normalize, I assume they want it rescaled to 0-255 so you can use rescale() or mat2gray(). Sounds like you can use rgb2gray() - it did not explicitly say that you could NOT use it. I imagine you can use other built-in functions like uint8(), rescale(), and mat2gray() also.
  2 Comments
Image Analyst
Image Analyst on 31 Oct 2020
There is also an imsplit() function that you might be interested in
[R, G, B] = imsplit(double(rgbImage));
grayScaleImage = 0.2989 * R + 0.5870 * G + 0.1140 * B; % The hint given in the problem statement.
% Now normalize with rescale(), cast to uint8() and call imshow().

Sign in to comment.


DGM
DGM on 25 Apr 2022
Assuming that the input is an RGB image and that the intended grayscale representation is luma and not something else:
% get an RGB image
rgbpict = imread('peppers.png');
% pick luma constants
factors = permute([0.299 0.587 0.114],[1 3 2]); % Rec 470/601 (analog/digital SD video)
%factors = permute([0.2126 0.7152 0.0722],[1 3 2]); % Rec 709 (HDTV video)
% calculate the weighted sum
ypict = sum(bsxfun(@times,im2double(rgbpict),factors),3);
ypict = im2uint8(ypict); % if you want uint8 output
imshow(ypict)

Community Treasure Hunt

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

Start Hunting!