【问题标题】:Convert a color image to grayscale in MATLAB without rgb2gray [duplicate]在没有rgb2gray的MATLAB中将彩色图像转换为灰度[重复]
【发布时间】:2016-11-06 20:07:54
【问题描述】:

我想将我的彩色图像转换为灰度图像并避免使用rgb2gray 命令。

【问题讨论】:

    标签: matlab image-processing grayscale


    【解决方案1】:

    那么:

    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));
    

    【讨论】:

    • 我是 MATLAB 新手,这个命令对我来说很复杂,你能用更简单的吗?
    • 比单一功能更简单?什么??
    • 我用了那个,但我面对的是一张空白图片!!!
    • 如果您的原始图像是 uint8,那么您可能必须将其类型转换回该图像。我会编辑。
    • 这对我帮助很大,谢谢。
    【解决方案2】:

    这里是对 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

    【讨论】:

      【解决方案3】:

      函数rgb2gray 消除了huesaturation,并保留了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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-11
        • 1970-01-01
        • 2010-12-19
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 2016-01-11
        相关资源
        最近更新 更多