【问题标题】:Why imread function in matlab converts a grayscale image to an image containing 3 channels?为什么matlab中的imread函数将灰度图像转换为包含3个通道的图像?
【发布时间】:2021-02-28 01:14:12
【问题描述】:

我有一张灰度图像,我在 matlab 中使用imread 函数来读取它,但它有 3 个通道。我使用了rgb2gray,现在通道数为 1,强度范围为 0 到 255。问题是我需要将图像转换为双精度,但是当我这样做时,我会收到黑白图像。这是代码和图像:

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

【问题讨论】:

  • 如何显示图像?请提供所有相关的代码,尤其是那些没有做你认为会做的事情的代码?
  • 非常感谢。我使用 imshow 来显示图像。我使用了 im2double 和 imshow(refimg,[]) 问题解决了。

标签: image matlab image-processing


【解决方案1】:

仅仅因为图像只包含灰色阴影并不意味着图像只有一个通道。图像可以是 RGB 格式,并且所有通道的值对于每个像素都是相等的。下面是一个例子来证明这一点:

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

结果:

没有。 RGB-24bit.bmp 通道数:3
gray-8bit.bmp 的通道数:1

关于像 BW 一样显示的图像,当您尝试使用 double() 将整数矩阵转换为双精度矩阵时,它只会转换数据类型而不会更改实际值。因此,在您的代码中,refimg 在 [0..255] 区间中包含双精度值。现在,imshow() 期望双精度值在[0..1] 区间内,并将值等于或大于1 的所有像素显示为白色像素。试试imshow(refimg, []),它会根据refimg 中的像素值范围来缩放显示。 但是将整数图像转换为双精度图像的正确方法是使用im2double(),它还将输出从整数数据类型重新缩放到范围 [0, 1]。

【讨论】:

  • 非常感谢。我使用了 im2double 并且它有效。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 2018-03-29
  • 2011-04-18
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多