RGB to Grayscale without using rgb2gray

조회 수: 30 (최근 30일)
Soomin Lee
Soomin Lee 2021년 11월 22일
답변: DGM 2022년 10월 21일
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);

답변 (3개)

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');

DGM
DGM 2022년 10월 21일
This answer covers conversions for both BT601 luma (what rgb2gray() and im2gray() use) and BT709 luma.
This answer covers conversions to other grayscale representations of color images (I, V, L, Y, L*)
Alternatively, MIMT mono() can simply return any of the above, without the need for IPT or tedious conversions.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by