简体   繁体   中英

Why imread function in matlab converts a grayscale image to an image containing 3 channels?

I have a grayscale image and I used imread function in matlab to read it but it has 3 channels. I used rgb2gray and now the number of channels is 1 and the intensity range is 0 to 255. The problem is that I need to convert my image to double precision but when I do this I receive a black and white image. Here is the code and image:

refimg = double(rgb2gray((imread('D:/img.jpg'))));

在此处输入图片说明

Just because an image contains only gray shade does not mean that the image has only one channel. The image can be in RGB format and the values of all channels be equal for each of its pixels. Here is an example that demonstrates this:

% reading a colored RGB image and convert it to grayscale
I = rgb2gray(imread('peppers.png'));
% saving the grayscale image as 24-bit bitmap file
imwrite(repmat(I, 1, 1, 3), 'RGB-24bit.bmp')
% saving same image as 8-bit bitmap file
imwrite(I, 'gray-8bit.bmp')
% reading both files
I24 = imread('RGB-24bit.bmp');
I8 = imread('gray-8bit.bmp');
% displaying no of channels
fprintf('No. of channels of RGB-24bit.bmp: %d\n', size(I24, 3));
fprintf('No. of channels of gray-8bit.bmp: %d\n', size(I8, 3));
% displaying images
subplot 121, imshow(I24), title('RGB-24bit.bmp')
subplot 122, imshow(I8), title('gray-8bit.bmp')

and the results:

No. of channels of RGB-24bit.bmp: 3
No. of channels of gray-8bit.bmp: 1

在此处输入图片说明

And about the image being displayed like BW, when you try to convert an integer matrix to double using double() , it only converts the data type and does not change the actual values. So, in your code, refimg contains double values in [0..255] interval. Now, imshow() expects doubles to be in [0..1] interval and displays all pixels with values equal or grater than 1 as white pixels. Try imshow(refimg, []) that scales the display based on the range of pixel values in refimg . But the correct way to convert an integer image to double is using im2double() which also rescales the output from integer data types to the range [0, 1].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM