【发布时间】:2016-11-06 20:07:54
【问题描述】:
我想将我的彩色图像转换为灰度图像并避免使用rgb2gray 命令。
【问题讨论】:
标签: matlab image-processing grayscale
我想将我的彩色图像转换为灰度图像并避免使用rgb2gray 命令。
【问题讨论】:
标签: matlab image-processing grayscale
那么:
I_grey = mean(I_colour, 3);
您可能需要将其转换为 uint8 才能查看它:
I_grey = uint8(mean(I_colour, 3));
或者,如果您想真正准确,您实际上应该找到一个加权平均值。有关权重选项,请参阅此问题的答案:Formula to determine brightness of RGB color
这是一个例子:
W = permute([0.3086, 0.6094, 0.0820], [3,1,2]);
I_grey = uint8(sum(bsxfun(@times, double(I_colour), W),3));
【讨论】:
这里是对 Dan 的回答的一些修改,以及用于回答您的问题的其他内容。
代码 -
%// Load image
I_colour = imread('pic1.jpg');
%// Dan's method with the correct (correct if you can rely on MATLAB's paramters,
%// otherwise Dan's mentioned paramters could be correct, but I couuldn't verify)
%// parameters** as listed also in RGB2GRAY documentation and at -
%// http://www.mathworks.com/matlabcentral/answers/99136
W = permute([0.2989, 0.5870, 0.1140], [3,1,2]);
I_grey = sum(bsxfun(@times, double(I_colour), W),3);
%// MATLAB's in-built function
I_grey2 = double(rgb2gray(I_colour));
%// Error checking between our and MATLAB's methods
error = rms(abs(I_grey(:)-I_grey2(:)))
figure,
subplot(211),imshow(uint8(I_grey));
subplot(212),imshow(uint8(I_grey2));
Mathworks 家伙用简单易懂的代码很好地回答了这个问题 - http://www.mathworks.com/matlabcentral/answers/99136
【讨论】:
函数rgb2gray 消除了hue和saturation,并保留了luminance(brightness)的信息。
因此,您可以使用以下公式将位于 i 和 j 的像素转换为灰度。
grayScaleImage(i,j) = 0.298*img(i,j,1)+0.587*img(i,j,2)+0.114*img(i,j,3)
img(i,j,1) 是红色像素的值。
img(i,j,2) 是绿色像素的值。
img(i,j,3) 是蓝色像素的值。
grayScaleImage(i,j) 是范围[0..255]内的灰度像素值
img = imread('example.jpg');
[r c colormap] = size(img);
for i=1:r
for j=1:c
grayScaleImg(i,j) = 0.298*img(i,j,1)+0.587*img(i,j,2)+0.114*img(i,j,3);
end
end
imshow(grayScaleImg);
【讨论】: