图像在 skimage 中包含 0 或 1 错误以外的值

image contains values other than 0 or 1 error in skimage

我有这张图片:

我想将此代码用于 sckimage 以获得图像的骨架和细化,

from skimage.morphology import skeletonize, thin
import cv2 

image =cv2.imread('1.png',0)


skeleton = skeletonize(image)
thinned = thin(image)
thinned_partial = thin(image, max_iter=25)

fig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True)
ax = axes.ravel()

ax[0].imshow(image, cmap=plt.cm.gray, interpolation='nearest')
ax[0].set_title('original')
ax[0].axis('off')

ax[1].imshow(skeleton, cmap=plt.cm.gray, interpolation='nearest')
ax[1].set_title('skeleton')
ax[1].axis('off')

ax[2].imshow(thinned, cmap=plt.cm.gray, interpolation='nearest')
ax[2].set_title('thinned')
ax[2].axis('off')


fig.tight_layout()
plt.show()

但它给我的错误是 'line 98, in skeletonize, VaueError : image contains values other than 0 and 1'

谁能帮我解决这个问题?

Skeletonize 仅适用于 binary/boolean 图像,这意味着只有两个值的图像。按照惯例,这些值应为 0 或 1,或者 False 或 True。

在你的例子中,虽然你的图像看起来只有黑色和白色,但它实际上有一些中间灰度值:

In [1]: import numpy as np
In [2]: from skimage import io
In [3]: image = io.imread('https://i.stack.imgur.com/awMuQ.png')
In [4]: np.unique(image)
Out[3]: 
array([  0,  14,  23,  27,  34,  38,  46,  53,  57,  66,  69,  76,  79,
        86,  89, 102, 105, 114, 120, 124, 135, 142, 145, 150, 158, 162,
       169, 172, 181, 183, 189, 199, 207, 213, 220, 226, 232, 235, 238,
       239, 244, 245, 249, 252, 255], dtype=uint8)

要获得二值图像,您可以使用阈值处理,同样来自 scikit-image:

In [5]: from skimage import morphology, filters
In [6]: binary = image > filters.threshold_otsu(image)
In [7]: np.unique(binary)
Out[7]: array([False,  True])
In [8]: skeleton = morphology.skeletonize(binary)
In [9]: