Change RGB image to gray without rgb2gray function
86 views (last 30 days)
Load a RGB Image and convert to grayscale as shown in the following example.
0.2989 * R + 0.5870 * G + 0.1140 * B
Reference function rgb2gray( ) in MATLAB
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.
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)
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.
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