基于边缘和基于区域的分割比较#

在这个示例中,我们将看到如何从背景中分割对象。我们使用 skimage.data 中的 coins 图像,该图像显示了几个硬币在较暗的背景上被勾勒出来。

import numpy as np
import matplotlib.pyplot as plt

from skimage import data
from skimage.exposure import histogram

coins = data.coins()
hist, hist_centers = histogram(coins)

fig, axes = plt.subplots(1, 2, figsize=(8, 3))
axes[0].imshow(coins, cmap=plt.cm.gray)
axes[0].set_axis_off()
axes[1].plot(hist_centers, hist, lw=2)
axes[1].set_title('histogram of gray values')
histogram of gray values
Text(0.5, 1.0, 'histogram of gray values')

阈值化#

分割硬币的一个简单方法是根据灰度值的直方图选择一个阈值。不幸的是,对此图像进行阈值处理会得到一个二值图像,该图像要么遗漏硬币的重要部分,要么将背景的部分与硬币合并:

fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)

axes[0].imshow(coins > 100, cmap=plt.cm.gray)
axes[0].set_title('coins > 100')

axes[1].imshow(coins > 150, cmap=plt.cm.gray)
axes[1].set_title('coins > 150')

for a in axes:
    a.set_axis_off()

fig.tight_layout()
coins > 100, coins > 150

基于边缘的分割#

接下来,我们尝试使用基于边缘的分割来描绘硬币的轮廓。为此,我们首先使用Canny边缘检测器获取特征的边缘。

from skimage.feature import canny

edges = canny(coins)

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(edges, cmap=plt.cm.gray)
ax.set_title('Canny detector')
ax.set_axis_off()
Canny detector

然后使用数学形态学填充这些轮廓。

from scipy import ndimage as ndi

fill_coins = ndi.binary_fill_holes(edges)

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(fill_coins, cmap=plt.cm.gray)
ax.set_title('filling the holes')
ax.set_axis_off()
filling the holes

通过设置有效对象的最小尺寸,可以轻松移除小型的杂散对象。

from skimage import morphology

coins_cleaned = morphology.remove_small_objects(fill_coins, 21)

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(coins_cleaned, cmap=plt.cm.gray)
ax.set_title('removing small objects')
ax.set_axis_off()
removing small objects

然而,这种方法并不十分稳健,因为未完全闭合的轮廓无法正确填充,如上图中的一个未填充的硬币所示。

基于区域的分割#

因此,我们尝试使用基于区域的方法,利用分水岭变换。首先,我们使用图像的Sobel梯度找到一个高程图。

from skimage.filters import sobel

elevation_map = sobel(coins)

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(elevation_map, cmap=plt.cm.gray)
ax.set_title('elevation map')
ax.set_axis_off()
elevation map

接下来,我们根据灰度值直方图的极端部分找到背景和硬币的标记。

markers

最后,我们使用分水岭变换从上述确定的标记开始填充高程图的区域:

segmentation

最后这种方法效果更好,硬币可以被单独分割和标记。

from skimage.color import label2rgb

segmentation_coins = ndi.binary_fill_holes(segmentation_coins - 1)
labeled_coins, _ = ndi.label(segmentation_coins)
image_label_overlay = label2rgb(labeled_coins, image=coins, bg_label=0)

fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)
axes[0].imshow(coins, cmap=plt.cm.gray)
axes[0].contour(segmentation_coins, [0.5], linewidths=1.2, colors='y')
axes[1].imshow(image_label_overlay)

for a in axes:
    a.set_axis_off()

fig.tight_layout()

plt.show()
plot coins segmentation

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

由 Sphinx-Gallery 生成的图库