Search code examples
pythonimage-processingscikit-image

image contains values other than 0 or 1 error in skimage


i have this image :

enter image description here

and i wanna use this code to of sckimage to get skeleton and thining of my image,

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()

but its giving me the error saying 'line 98, in skeletonize, VaueError : image contains values other than 0 and 1'

can anyone help me how i can solve it ?


Solution

  • Skeletonize only works on binary/boolean images, which means images with only two values. By convention, these values should be 0 or 1, or False or True.

    In your case, although your image looks like it only has black and white, it actually has some intermediate gray values:

    In [1]: import numpy as np
    In [2]: from skimage import io
    In [3]: image = io.imread('https://i.sstatic.net/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)
    
    

    To get a binary image, you can use thresholding, also from 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]: