Skip to content

Instantly share code, notes, and snippets.

@jsheedy
Created June 10, 2016 23:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jsheedy/3913ab49d344fac4d02bcc887ba4277d to your computer and use it in GitHub Desktop.
Save jsheedy/3913ab49d344fac4d02bcc887ba4277d to your computer and use it in GitHub Desktop.
OpenCV-Python skeletonize function
def skeletonize(img):
""" OpenCV function to return a skeletonized version of img, a Mat object"""
# hat tip to http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/
img = img.copy() # don't clobber original
skel = img.copy()
skel[:,:] = 0
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))
while True:
eroded = cv2.morphologyEx(img, cv2.MORPH_ERODE, kernel)
temp = cv2.morphologyEx(eroded, cv2.MORPH_DILATE, kernel)
temp = cv2.subtract(img, temp)
skel = cv2.bitwise_or(skel, temp)
img[:,:] = eroded[:,:]
if cv2.countNonZero(img) == 0:
break
return skel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment