4

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!!!

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Daniel Yan
  • 41
  • 1
  • 2

1 Answers1

8

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.

Stefan van der Walt
  • 7,165
  • 1
  • 32
  • 41
  • I think the big thing that you did, but didn't emphasize is that converting to binary is going to clear up quite a bit.. I imagine slight differences in the white level of the original image was causing the skeleton artifacts. – Aaron Mar 20 '17 at 19:14
  • note the original image was a jpeg, which would suffer these often imperceptible artifacts. – Aaron Mar 20 '17 at 19:16
  • Silly me, I read the question in diagonal and didn't notice that the OP actually wanted the skeleton rather than the contour. – Tonechas Mar 20 '17 at 20:28
  • Thank you!! @Stefan, Aaron, Tonechas. With the code here, I have successfully drawn the skeleton image. You are really appreciated!! – Daniel Yan Mar 21 '17 at 13:03