# RGB to Grayscale without using rgb2gray

53 views (last 30 days)
Soomin Lee on 22 Nov 2021
Answered: yanqi liu on 2 Dec 2021
I need to convert RGB image to grayscale without using rgb2gray pre-made code.
I am already getting an error saying "Index in position 3 exceeds array bounds. Index must not exceed 1."
How do I convert RGB to grayscale without rgb2gray? Also, how do I convert back to rgb from grayscale?
RGB_image = ('peppers.png');
r = RGB_image(:,:,1);
g = RGB_image(:,:,2);
b = RGB_image(:,:,3);

Dave B on 22 Nov 2021
You can choose many approaches for converting to grayscale. For instance you could weight the three colors equally:
im_gray = mean(im,3); % take the average of red, green, blue values
im_gray = repmat(uint8(im_gray),[1 1 3]); % convert to integers and fill red, green, and blue values with the grayscale values
imshow(im_gray)
The weighting that im2gray uses is on the documentation page, it over-weights green and under-weights blue.
You can't take a converted grayscale image back to its RGB original, the color information is gone. However there are lots of deep learning algorithms for colorizing. You could search for "colorize deep learning" etc.

yanqi liu on 2 Dec 2021
convert RGB to grayscale without rgb2gray
convert back to rgb from grayscale
clc; clear all; close all;
RGB_image = double(RGB_image);
% split rgb channel
R = RGB_image(:,:,1);
G = RGB_image(:,:,2);
B = RGB_image(:,:,3);
% use weight, self define
gray = 0.299 * R + 0.587 * G + 0.114 * B;
% gray to rgb, self define
rgb = zeros(size(gray,1), size(gray,2), 3);
rgb(:,:,1) = gray;
rgb(:,:,2) = 0.5*gray;
rgb(:,:,3) = 0.8*gray;
% display
figure;
subplot(1, 3, 1); imshow(mat2gray(RGB_image)); title('origin rgb');
subplot(1, 3, 2); imshow(mat2gray(gray)); title('gray');
subplot(1, 3, 3); imshow(mat2gray(rgb)); title('gray to rgb');