如何导入 Skimage 以分水岭分割图像?

How to import Skimage to segment an image with watershed?

我正在尝试使用 Skimage 来分割具有分水岭的图像,但我总是遇到此错误。请问有解决办法吗?

AttributeError: module 'skimage.morphology' has no attribute 'watershed'

源代码:https://scikit-image.org/docs/0.12.x/auto_examples/xx_applications/plot_coins_segmentation.html

import numpy as np
import matplotlib.pyplot as plt
import cv2

from skimage.feature import canny
from scipy import ndimage as ndi
from skimage import morphology
from skimage.filters import sobel
from skimage import data
from skimage.color import label2rgb


coins = data.coins()
hist = np.histogram(coins, bins=np.arange(0, 256))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3))
ax1.imshow(coins, cmap=plt.cm.gray, interpolation='nearest')
ax1.axis('off')
ax2.plot(hist[1][:-1], hist[0], lw=2)
ax2.set_title('histogram of grey values')

    # Threshold
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3), sharex=True, sharey=True)
ax1.imshow(coins > 100, cmap=plt.cm.gray, interpolation='nearest')
ax1.set_title('coins > 100')
ax1.axis('off')
ax1.set_adjustable('box')
ax2.imshow(coins > 150, cmap=plt.cm.gray, interpolation='nearest')
ax2.set_title('coins > 150')
ax2.axis('off')
ax2.set_adjustable('box')
margins = dict(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1)
fig.subplots_adjust(**margins)


elevation_map = sobel(coins)

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(elevation_map, cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
ax.set_title('elevation_map')

markers = np.zeros_like(coins)
markers[coins < 30] = 1
markers[coins > 150] = 2

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(markers, cmap=plt.cm.Spectral, interpolation='nearest')
ax.axis('off')
ax.set_title('markers')


segmentation = morphology.watershed(elevation_map, markers)

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(segmentation, cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
ax.set_title('segmentation')


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

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3), sharex=True, sharey=True)
ax1.imshow(coins, cmap=plt.cm.gray, interpolation='nearest')
ax1.contour(segmentation, [0.5], linewidths=1.2, colors='y')
ax1.axis('off')
ax1.set_adjustable('box')
ax2.imshow(image_label_overlay, interpolation='nearest')
ax2.axis('off')
ax2.set_adjustable('box')

fig.subplots_adjust(**margins)

plt.show()

Error on line : segmentation = morphology.watershed(elevation_map, markers)

您出于某种原因正在查看 scikit-image 的旧文档,版本 0.12。 (请参阅您共享的 URL 中的 0.12.x。)您可以在以下位置查看最新发布版本的示例:

https://scikit-image.org/docs/stable/auto_examples/

具体来说,对于您的代码,您需要将导入更新为 from skimage.segmentation import watershed