一、MATLAB Color Thresholder介绍
Color Thresholder工具箱可以根据不同颜色空间对颜色通道设置阈值,从而分割彩色图像。使用此工具箱,可以为彩色图像创建二值分割掩膜。
Color Thresholder工具箱支持四种颜色空间的分割。在每个颜色空间中,该工具箱将图像、三个颜色通道和所有像素的颜色值显示为三维颜色空间图中的点。可以通过为颜色通道值设置窗口或者在图像或三维颜色空间图中绘制 ROI 来选择掩膜中包含的颜色。
二、Color Thresholder基础教程
2.1 进入工具箱
打开应用程序->图像处理计算机视觉->Color Thresholder
也可以直接在命令行窗口输出命令:colorThresholder进入工具箱
2.2 导入图像
原始图像如下:
导入图像选择Load Image:
这里将气球图像ball加载到应用程序中,可以看到有四种颜色样式,分别为RGB,HSV,YCbCr以及Lab*。对于基于颜色的分割,请选择提供最佳颜色分离的颜色空间。使用鼠标旋转点云表示,以查看它们如何隔离各个颜色。使用Color Thresholder应用程序进行分割可能是一个迭代过程。在实现满足您需要的分割之前,请尝试几种不同的颜色空间。对于本例,通过选择HSV颜色空间开始该过程。
2.3 调整阈值
使用图形界面调整HSV通道参数,并在界面窗口中观察结果,当结果令人满意时,选择应用程序窗口右上角的导出图标,将结果导出为图像或函数。
2.4 导出为函数
导出MATLAB函数后可以将相同的阈值参数应用于MATLAB中的任何图像,而无需重新使用Color Thresholder应用程序。这对于自动化很有用。
导出函数源代码的示例代码如下。
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 09-Nov-2021
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.941;
channel1Max = 0.998;
% Define thresholds for channel 2 based on histogram settings
channel2Min = 0.327;
channel2Max = 1.000;
% Define thresholds for channel 3 based on histogram settings
channel3Min = 0.292;
channel3Max = 1.000;
% 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;
% 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
请注意此代码中定义的通道最小值和最大值。要使用该函数,请确保将该函数从createMask重命名为更具体的名称并保存。
参考: