分水岭分割#

分水岭是一种用于**分割**的经典算法,即用于分离图像中的不同对象。

从用户定义的标记开始,分水岭算法将像素值视为局部地形(海拔)。该算法从标记处淹没盆地,直到归属于不同标记的盆地在分水岭线上相遇。在许多情况下,标记被选择为图像的局部最小值,从这些局部最小值开始淹没盆地。

在下面的示例中,需要分离两个重叠的圆圈。为此,计算一个图像,该图像到背景的距离。此距离的最大值(即距离相反数的最小值)被选为标记,并且从这些标记淹没盆地沿着分水岭线分离两个圆圈。

有关该算法的更多详细信息,请参阅维基百科

Overlapping objects, Distances, Separated objects
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage as ndi

from skimage.segmentation import watershed
from skimage.feature import peak_local_max


# Generate an initial image with two overlapping circles
x, y = np.indices((80, 80))
x1, y1, x2, y2 = 28, 28, 44, 52
r1, r2 = 16, 20
mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2
mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2
image = np.logical_or(mask_circle1, mask_circle2)

# Now we want to separate the two objects in image
# Generate the markers as local maxima of the distance to the background
distance = ndi.distance_transform_edt(image)
coords = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image)
mask = np.zeros(distance.shape, dtype=bool)
mask[tuple(coords.T)] = True
markers, _ = ndi.label(mask)
labels = watershed(-distance, markers, mask=image)

fig, axes = plt.subplots(ncols=3, figsize=(9, 3), sharex=True, sharey=True)
ax = axes.ravel()

ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].set_title('Overlapping objects')
ax[1].imshow(-distance, cmap=plt.cm.gray)
ax[1].set_title('Distances')
ax[2].imshow(labels, cmap=plt.cm.nipy_spectral)
ax[2].set_title('Separated objects')

for a in ax:
    a.set_axis_off()

fig.tight_layout()
plt.show()

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

由 Sphinx-Gallery 生成的图库