备注
转到结尾 以下载完整示例代码。或在您的浏览器中通过 Binder 运行此示例。
RGB 转 HSV#
这个例子说明了如何使用 RGB 到 HSV(色调、饱和度、值)转换 [1] 来促进分割过程。
通常,图像中的对象具有不同的颜色(色调)和亮度,因此这些特征可以用来分离图像的不同区域。在RGB表示中,色调和亮度表示为R、G、B通道的线性组合,而在HSV图像中,它们对应于单个通道(色调通道和值通道)。然后,通过简单地对HSV通道进行阈值处理,可以有效地对图像进行分割。
import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2hsv
我们首先加载RGB图像并提取色调和亮度通道:
rgb_img = data.coffee()
hsv_img = rgb2hsv(rgb_img)
hue_img = hsv_img[:, :, 0]
value_img = hsv_img[:, :, 2]
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(8, 2))
ax0.imshow(rgb_img)
ax0.set_title("RGB image")
ax0.axis('off')
ax1.imshow(hue_img, cmap='hsv')
ax1.set_title("Hue channel")
ax1.axis('off')
ax2.imshow(value_img)
ax2.set_title("Value channel")
ax2.axis('off')
fig.tight_layout()

然后我们在色调通道上设置一个阈值,以将杯子与背景分离:
hue_threshold = 0.04
binary_img = hue_img > hue_threshold
fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(8, 3))
ax0.hist(hue_img.ravel(), 512)
ax0.set_title("Histogram of the Hue channel with threshold")
ax0.axvline(x=hue_threshold, color='r', linestyle='dashed', linewidth=2)
ax0.set_xbound(0, 0.12)
ax1.imshow(binary_img)
ax1.set_title("Hue-thresholded image")
ax1.axis('off')
fig.tight_layout()

我们最终在Value通道上执行额外的阈值处理,以部分去除杯子的阴影:
fig, ax0 = plt.subplots(figsize=(4, 3))
value_threshold = 0.10
binary_img = (hue_img > hue_threshold) | (value_img < value_threshold)
ax0.imshow(binary_img)
ax0.set_title("Hue and value thresholded image")
ax0.axis('off')
fig.tight_layout()
plt.show()

脚本总运行时间: (0 分钟 0.382 秒)