competesingh
competesingh

Reputation: 135

Convert A Grayscale Image To Colored In Matlab

I am using the following lines of code to convert a colored image into grayscale image :

clc;
clear all;
close all;

[FileName,PathName] = uigetfile('*.jpg','Select the Cover Image');
file = fullfile(PathName,FileName);
disp(['User selected : ', file]);
cover = imread(file);
%cover = double(cover);

figure;
subplot(1,2,1);
imshow(uint8(cover),[]);
title('Cover image');


red = cover(:,:,1);
green = cover(:,:,2);
blue = cover(:,:,3);
a = zeros(size(cover, 1), size(cover, 2));

just_red = cat(3, red, a, a);
figure, imshow(just_red);

just_green = cat(3, a, green, a);
figure, imshow(just_green);

just_blue = cat(3, a, a, blue);
figure, imshow(just_blue);

[r1 r2 a] = size(just_red);
disp(a); disp(r1); disp(r2);
coverbw = rgb2gray(cover);

original = gray2rgb(coverbw);
figure, imshow(original);

After converting the original image to grayscale, I want to convert the grayscale image back into the original colored one. I tried using the following line of code to do the job :

original = gray2rgb(coverbw);

But I was getting the following error :

??? Undefined function or method 'gray2rgb' for input arguments of type 'uint8'.

Error in ==> main at 35
    original = gray2rgb(coverbw);

Can someone help me to get the original image from its grayscale version i.e. coverbw instead of combining the three separate components of red, green and blue color images ??

Thanks.

Upvotes: 2

Views: 3943

Answers (1)

Shai
Shai

Reputation: 114786

When converting RGB image to gray you lose color information per-pixel.
The gray value I per pixel i, j is determined by the formula:

I(i,j) = 0.299*R(i,j) + 0.587*G(i,j) + 0.114*B(i,j)

Mathematically, it means that if you know R, G and B you can determine I.
But, if you know only I you cannot recover R, G and B since you have a single equation with three unknowns and therefore there can be infinitely many possible color combinations that produce the same intensity I.

If you are working on scrambling of 2D images, you can treat each channel R, G and B as an independent 2D signal, scramble each one and then combine the reconstructed signals to a color image at the end by

rgb = cat(3, recoveredR, recoveredG recoveredB );

Upvotes: 4

Related Questions