分水嶺變換是一種用於圖像分割的方法,特別適用於分開相互接觸的對象。這種方法將灰度圖像視為地形地形,其中低強度區域表示谷底,而高強度區域表示山峰。分水嶺線表示分離這些山峰的地方。
以下是使用分水嶺變換進行圖像分割的 Python 範例:
from skimage.segmentation import watershed
from skimage.feature import peak_local_max
from scipy import ndimage
def watershed_segmentation(image):
"""
Segment an image using the watershed transformation.
Parameters:
- image: 2D numpy array representing the grayscale image
Returns:
- segmented image
"""
# Calculate distance map
distance_map = ndimage.distance_transform_edt(image)
# Find local maxima of the distance map
local_maxi = peak_local_max(distance_map, indices=False, footprint=np.ones((3, 3)), labels=image)
# Label the maxima
markers = ndimage.label(local_maxi)[0]
# Apply watershed transformation
segmented = watershed(-distance_map, markers, mask=image)
return segmented
# Segment the provided image using watershed transformation
watershed_img = watershed_segmentation(new_provided_img)
# Display the original and watershed segmented images
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(new_provided_img, cmap='gray')
ax[0].set_title('Original Image')
ax[0].axis('off')
ax[1].imshow(watershed_img, cmap='tab20b')
ax[1].set_title('Watershed Segmented Image')
ax[1].axis('off')
plt.tight_layout()
plt.show()
如上所示,左側是您提供的原始圖像,而右側是使用分水嶺變換得到的分割結果。
在這個過程中,我首先計算了一個距離映射,其中每個像素的值表示其到最近非零像素的距離。接著,我找到距離映射的局部最大值,這些最大值作為分水嶺算法的標記。最後,我使用這些標記和距離映射應用分水嶺變換。
結果的每個唯一顏色代表一個分割區域。這些區域通常對應於圖像中的各個對象或部分。
分水嶺變換是一種強大的分割方法,但可能需要一些調整以獲得最佳結果。您可以根據需要調整方法中的參數來改變分割的外觀。