Created
October 18, 2017 02:51
-
-
Save garybradski/4647365be8a84947e86fe1ba8f0f0c30 to your computer and use it in GitHub Desktop.
Skeletonize a single channel opencv image or 2D numpy array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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