注意
移至結尾下載完整的範例程式碼。或透過 Binder 在您的瀏覽器中執行此範例
分水嶺分割#
分水嶺是一種用於分割的經典演算法,也就是在影像中分離不同的物件。
從使用者定義的標記開始,分水嶺演算法將像素值視為局部地形(高度)。該演算法從標記處淹沒盆地,直到屬於不同標記的盆地在分水嶺線上相遇。在許多情況下,標記會選擇為影像的局部最小值,從這些最小值淹沒盆地。
在下面的範例中,要分離兩個重疊的圓。為此,需要計算與背景距離的影像。此距離的最大值(即距離相反數的最小值)會被選為標記,並且從這些標記淹沒盆地會沿著分水嶺線分離兩個圓。
有關此演算法的更多詳細資訊,請參閱 維基百科。

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.169 秒)