RGB to Grayscale without using rgb2gray
58 views (last 30 days)
Show older comments
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);
0 Comments
Answers (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=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.
0 Comments
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 = 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');
0 Comments
DGM
on 21 Oct 2022
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.
0 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!