Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the skeleton of a binary image with scikit-image

I want to draw the skeleton of the following image:

original image

I've tried with the following Python code:

import cv2
from skimage import morphology, color
import matplotlib.pyplot as plt

image = cv2.imread(r'C:\Users\Administrator\Desktop\sample.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image=color.rgb2gray(image)

skeleton =morphology.medial_axis(image)

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))

ax1.imshow(image, cmap=plt.cm.gray)
ax1.axis('off')
ax1.set_title('original', fontsize=20)

ax2.imshow(skeleton, cmap=plt.cm.gray)
ax2.axis('off')
ax2.set_title('skeleton', fontsize=20)

fig.tight_layout()
plt.show()

And I got the following skeleton:

enter image description here

This doesn't look like the right skeleton image. I don't know what's going wrong.

Can anyone help me on this? Any help would be appreciated!!!

like image 736
Daniel Yan Avatar asked Feb 05 '23 20:02

Daniel Yan


1 Answers

Applying the medial axis as in your example:

from skimage import img_as_bool, io, color, morphology
import matplotlib.pyplot as plt

image = img_as_bool(color.rgb2gray(io.imread('CIBUv.png')))
out = morphology.medial_axis(image)

f, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(image, cmap='gray', interpolation='nearest')
ax1.imshow(out, cmap='gray', interpolation='nearest')
plt.show()

yields

Medial Axis of binary image

Note that, as @Aaron mentions below, converting to a boolean image first helps here, because your original image was stored in JPEG which could introduce small fluctuations in pixel values.

You can also replace medial_axis with skeletonize for a different algorithm.

If you want the outline as described in @Tonechas's answer, then look at edge detection methods.

like image 190
Stefan van der Walt Avatar answered Feb 07 '23 17:02

Stefan van der Walt