【问题标题】:Color only a segment of an image in Matlab在 Matlab 中只为图像的一部分着色
【发布时间】:2017-02-24 16:27:24
【问题描述】:

我试图在 Matlab 中只为图像的一部分着色。例如,我加载一个 RGB 图像,然后我使用 Otsu 的方法 (graythresh) 获得一个蒙版。在应用im2bw 并以graythresh 作为阈值后,我只想将颜色保留在具有1 值的像素中。例如:

image = imread('peppers.png');
thr = graythresh(image);
bw = im2bw(image, thr);

使用此代码,我获得以下二进制图像:

我的目标是保持白色像素中的颜色。

谢谢!

【问题讨论】:

    标签: image matlab image-processing colors


    【解决方案1】:

    您的问题错过了“并用黑色替换其余部分”。这里有两种方法:

    一个紧凑的解决方案:使用bsxfun

    newImage = bsxfun(@times, Image, cast(bw, 'like', Image));
    

    虽然我对上一个很满意,但您也可以看看这个循序渐进的方法:

    % separate the RGB layers:
    R = image(:,:,1);
    G = image(:,:,2);
    B = image(:,:,3);
    
    % change the values to zero or your desired color wherever bw is false:
    R(~bw) = 0;
    G(~bw) = 0;
    B(~bw) = 0;
    
    % concatenate the results:
    newImage = cat(3, R, G, B);
    

    这可以为您提供黑色区域的不同替换:

    更新:

    根据 cmets,bwfalse 区域应该替换为相同输入的灰度图像。这是实现它的方法:

    image = imread('peppers.png');
    thr = graythresh(image);
    bw = im2bw(image, thr);
    gr = rgb2gray(image); % generate grayscale image from RGB
    newImage(repmat(~bw, 1, 1, 3)) = repmat(gr(~bw), 1, 1, 3); % substitude values
    % figure; imshow(newImage)
    

    有了这个结果:

    【讨论】:

    【解决方案2】:

    关于如何替换我们不关心的像素,我还有另一个建议。这通过为bw 图像中存在黑色像素的每个切片创建线性索引来工作。与find 的结果相加是因为bw 只是image 的一个“切片”的大小,这就是我们获取其他两个切片的索引的方式。

    启动 MATLAB 2016b:

    image(find(~bw)+[0 numel(bw)*[1 2]]) = NaN;
    

    在旧版本中:

    image(bsxfun(@plus,find(~bw),[0 numel(bw)*[1 2]])) = NaN;
    

    然后imshow(image) 给出:

    请注意,NaN 将转换为 0 以获取 integer classes


    在澄清其他像素应保持灰色版本后,请参阅以下代码:

    % Load image:
    img = imread('peppers.png');
    % Create a grayscale version:
    grayimg = rgb2gray(img);
    % Segment image:
    if ~verLessThan('matlab','9.0') && exist('imbinarize.m','file') == 2
      % R2016a onward:
      bw = imbinarize(grayimg);
      % Alternatively, work on just one of the color channels, e.g. red:
      % bw = imbinarize(img(:,:,1));
    else
      % Before R2016a:
      thr = graythresh(grayimg);
      bw = im2bw(grayimg, thr);
    end
    output_img = repmat(grayimg,[1 1 3]);
    colorpix = bsxfun(@plus,find(bw),[0 numel(bw)*[1 2]]);
    output_img(colorpix) = img(colorpix);
    figure; imshow(output_img);
    

    仅使用红色通道进行二值化时的结果:

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2012-06-26
      • 2013-02-18
      • 1970-01-01
      相关资源
      最近更新 更多