我正在尝试获取一个图像,其中除了几个彩色对象之外的所有内容都变灰,如下所示:

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

我尝试应用阈值过程然后对图像进行二值化,这给了我以下结果(掩码在左侧,乘法结果在右侧):

现在我正在尝试结合所有这些面具。我应该使用if循环将它组合成一个图像还是有更好的方法?我尝试使用(&,&,&),但它变成了黑色图像。
我正在尝试获取一个图像,其中除了几个彩色对象之外的所有内容都变灰,如下所示:

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

我尝试应用阈值过程然后对图像进行二值化,这给了我以下结果(掩码在左侧,乘法结果在右侧):

现在我正在尝试结合所有这些面具。我应该使用if循环将它组合成一个图像还是有更好的方法?我尝试使用(&,&,&),但它变成了黑色图像。
您的原始图像有 7 个不同的区域:5 个彩色提示、手和背景。那么问题就变成了,我们如何忽略墙壁和手,这恰好是两个最大的区域,只保留提示的颜色。
如果您的 MATLAB 许可证允许,我建议您使用Color Thresholder App ( colorThresholder),它可以让您在图像中找到合适的颜色表示。试验一分钟,我可以说L*a*b*色彩空间允许区域/颜色之间的良好分离:
然后我们可以导出这个函数,得到以下结果:
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
现在您有了遮罩,我们可以轻松地将原始图像转换为灰度,沿第三维复制它,然后使用逻辑索引从原始图像中获取彩色像素:
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
产生:
要组合掩码,请使用|(逐元素逻辑 OR),而不是&(逻辑 AND)。
mask = mask1 | mask2 | mask3;