RGB to Grayscale without using rgb2gray

조회 수: 51(최근 30일)
Soomin Lee
Soomin Lee 2021년 11월 22일
답변: yanqi liu 2021년 12월 2일
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);

답변(2개)

Dave B
Dave B 2021년 11월 22일
You can choose many approaches for converting to grayscale. For instance you could weight the three colors equally:
im=imread('peppers.png');
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
yanqi liu 2021년 12월 2일
convert RGB to grayscale without rgb2gray
convert back to rgb from grayscale
clc; clear all; close all;
RGB_image = imread('peppers.png');
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');

Community Treasure Hunt

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

Start Hunting!

Translated by