Skip to content

Instantly share code, notes, and snippets.

@garybradski
Created October 18, 2017 02:51
Show Gist options
  • Select an option

  • Save garybradski/4647365be8a84947e86fe1ba8f0f0c30 to your computer and use it in GitHub Desktop.

Select an option

Save garybradski/4647365be8a84947e86fe1ba8f0f0c30 to your computer and use it in GitHub Desktop.
Skeletonize a single channel opencv image or 2D numpy array
def skeletonize(img):
'''
Adapted from:
https://opencvpython.blogspot.com/2012/05/skeletonization-using-opencv-python.html
'''
assert len(img.shape) == 2 #make sure its single channel
size = np.size(img)
tenth_size = size/10
skel = np.zeros(img.shape,np.uint8)
ret,img = cv2.threshold(img,127,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
done = False
while( not done):
eroded = cv2.erode(img,element)
temp = cv2.dilate(eroded,element)
temp = cv2.subtract(img,temp)
skel = cv2.bitwise_or(skel,temp)
img = eroded.copy()
zeros = size - cv2.countNonZero(img)
if zeros==size:
done = True
return skel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment