MATLAB: Matrix to rgb conversion

colormatrix to color conversion

When we write
i=imread('test.jpg');
if test.jpg is a colored image then it returns us i as a 3D matrix.
if we write
figure,imshow(i)
it shows the colored image test.jpg
but if we assign the values in i to another variable using the following syntax:
a=i(:,:,1); a=i(:,:,2); a=i(:,:,3);
then if i write
figure,imshow(a)
it does not return me the colored image as test.jpg
can any one say why this happen? How can i get the make a rgb image if i assign value to a 3D matrix manually how can i get the corresponding colored rgb image?

Best Answer

The reason why you are having the problem is that when you call the ZEROS function, you are getting an array of doubles, whereas a jpg image is of type uint8.
I = imread('test.jpg');
figure
imshow(I)
a = zeros(size(I),'uint8'); % Or, a = zeros(size(I),class(I));
a(:,:,1) = I(:,:,1);
a(:,:,2) = I(:,:,2);
a(:,:,3) = I(:,:,3);
figure
imshow(a)
Note that the above is a horrible way to copy any data from one array to another. Simply use:
a = I; % Don't use variable name i!