import numpy as np
from skimage.io import imread, imsave
import skimage.filters as filters
from skimage.segmentation import active_contour
import matplotlib.pyplot as plt
from skimage.draw import polygon
#---------------------------------
img = imread('A.jpg')
mask = imread('label.png')
def activeContour(img, mask, alpha=0.015, beta=10, gamma=0.00000001, iterations=1000, max_step=0.7):
lb_list = np.unique(mask)
Result = np.zeros_like(img)
for lb in lb_list:
if(lb != 0):
s = np.where(mask == lb)
r = s[0].astype(np.uint8)
c = s[1].astype(np.uint8)
init = np.array([r, c]).T
#-------PreProcessing----------------------------
img2 = filters.gaussian(img, 3)
#------- Active Contour ------------------------
snake = active_contour(img2, init, alpha=alpha, beta=beta, gamma=gamma, coordinates='rc',
max_px_move=max_step, max_iterations=iterations)
#------------------------------------------------
Result[tuple(np.round(snake).astype(int).T)] += lb
return Result.T
def sortVertices(array):
s = np.where(array != 0)
yr = s[0].astype(np.uint8)
xc = s[1].astype(np.uint8)
center_xc = np.sum(xc)/xc.shape
center_yr = np.sum(yr)/yr.shape
theta = np.arctan2(yr-center_yr, xc-center_xc) * 180 / np.pi
indices = np.argsort(theta)
x = xc[indices]
y = yr[indices]
return x,y
res2 = activeContour(img, mask, alpha=0.15, beta= 100, gamma= 0.000001)
labels = np.unique(res2)
ctr = 25
for label in labels:
if label != 0:
img2 = np.zeros_like(img)
res = res2.copy()
res[res != label]=0
if np.count_nonzero(res)>1:
x, y = sortVertices(res)
rr, cc = polygon(x, y)
else:
rr, cc = np.where(res==label)
img2[rr, cc] = 2*ctr
img3 = (img2/img2.max())*img
plt.imshow(img3, cmap='gray')
plt.title('%d'%label)
plt.axis('off')
plt.show()
ctr+=1