Skeleton2.py 1.63 KB
import cv2
import numpy as np

def Skeletization(img, shape, size):
	if shape == '1':
		shape = cv2.MORPH_RECT
	elif shape == '2':
		shape = cv2.MORPH_ELLIPSE
	elif shape == '3':
		shape = cv2.MORPH_CROSS
	else:
		return
	
	cv2.normalize(img, img, 0, 255, cv2.NORM_MINMAX)
	skeleton = np.zeros(img.shape, np.uint8)
	eroded = np.zeros(img.shape, np.uint8)
	temp = np.zeros(img.shape, np.uint8)

	_,thresh = cv2.threshold(img, 127, 255, 0)
	
	kernel = cv2.getStructuringElement(shape,(int(size), int(size)))

	while(True):
		cv2.erode(thresh, kernel, eroded)
        	cv2.dilate(eroded, kernel, temp)
        	cv2.subtract(thresh, temp, temp)
        	cv2.bitwise_or(skeleton, temp, skeleton)
        	thresh, eroded = eroded, thresh 

        	if cv2.countNonZero(thresh) == 0:
			break

	kernel = np.ones((20,20), np.uint8)
	skeleton = cv2.morphologyEx(skeleton, cv2.MORPH_CLOSE, kernel)
	cv2.imwrite('DefaultSkeleton.png', skeleton)
	cv2.imshow('skeleton', skeleton)
	return skeleton

def KernelChoice():
	image = None
	size = '0'
	choice = '0'
	print('\t\tSkeleton Menu\n')
	while (image is None):
		image = str(raw_input('\tImage to use? By default FondNoir.png \n'))
		if not image:
			image = 'FondNoir.png'
		image = cv2.imread(str(image),0)
	print('\t1. Rectangle\n\t2. Ellipse\n\t3. Cross\n')
	while choice < '1' or choice > '3': 
		choice = raw_input('\n\tKernel Choice. Rectangle by Default\n')
		if not choice:
			choice = '1'
	while int(size) % 2 == 0:
		size = raw_input('\n\tPlease specify the kernel size (Odd number). By default it\'s 3\n')
		if not size:
			size = '3'
	Skeletization(image, choice, size)

	cv2.waitKey(0)
	cv2.destroyAllWindows()
	
	return