组合口罩

时间:2018-12-25 11:44:49

标签: image matlab image-processing mask image-thresholding

我正在尝试获取一张图像,该图像除了灰色的几个彩色物体外,所有的东西都变灰,如下所示:

intended result

我的原始图像是这样的(颜色与上面的示例略有不同):

original image

我尝试应用阈值处理,然后对图像进行二值化处理,从而得到以下结果(掩码在左侧,乘法结果在右侧):

after thresholding

现在我正在尝试将所有这些蒙版组合在一起。我应该使用if循环将其合并为一个图像还是有更好的方法?我尝试使用(&,&,&),但它变成了黑色图像。

2 个答案:

答案 0 :(得分:4)

您的原始图像有7个不同的区域:5个彩色笔尖,手和背景。问题就变成了,我们如何不理会恰好是两个最大区域的墙和手,而只保留尖端的颜色。

如果您的MATLAB许可证允许,我建议您使用Color Thresholder AppcolorThresholder),它可以让您找到图像中颜色的合适表示形式。我尝试了一下,可以说L*a*b*颜色空间可以使区域/颜色之间实现良好的分离:

enter image description here

然后我们可以导出此函数,得到以下结果:

function [BW,maskedRGBImage] = createMask(RGB)
%createMask  Threshold RGB image using auto-generated code from colorThresholder app.
%  [BW,MASKEDRGBIMAGE] = createMask(RGB) thresholds image RGB using
%  auto-generated code from the colorThresholder app. The colorspace and
%  range for each channel of the colorspace were set within the app. The
%  segmentation mask is returned in BW, and a composite of the mask and
%  original RGB images is returned in maskedRGBImage.

% Auto-generated by colorThresholder app on 25-Dec-2018
%------------------------------------------------------


% Convert RGB image to chosen color space
I = rgb2lab(RGB);

% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.040;
channel1Max = 88.466;

% Define thresholds for channel 2 based on histogram settings
channel2Min = -4.428;
channel2Max = 26.417;

% Define thresholds for channel 3 based on histogram settings
channel3Min = -12.019;
channel3Max = 38.908;

% Create mask based on chosen histogram thresholds
sliderBW = (I(:,:,1) >= channel1Min ) & (I(:,:,1) <= channel1Max) & ...
  (I(:,:,2) >= channel2Min ) & (I(:,:,2) <= channel2Max) & ...
  (I(:,:,3) >= channel3Min ) & (I(:,:,3) <= channel3Max);
BW = sliderBW;

% Invert mask
BW = ~BW;

% Initialize output masked image based on input image.
maskedRGBImage = RGB;

% Set background pixels where BW is false to zero.
maskedRGBImage(repmat(~BW,[1 1 3])) = 0;

end

现在有了遮罩,我们可以轻松地将原始图像转换为灰度,沿3 rd 维度进行复制,然后使用逻辑索引从原始图像中获取彩色像素:

function q53922067
img = imread("https://i.stack.imgur.com/39WNm.jpg");

% Image segmentation:
BW = repmat( createMask(img), 1, 1, 3 ); % Note that this is the function shown above

% Keeping the ROI colorful and the rest gray:
gImg = repmat( rgb2gray(img), 1, 1, 3 ); % This is done for easier assignment later
gImg(BW) = img(BW);

% Final result:
figure(); imshow(gImg);
end

哪种产量:

enter image description here

答案 1 :(得分:1)

要组合掩码,请使用|(逐元素逻辑或),而不要使用&(逻辑与)。

mask = mask1 | mask2 | mask3;