def to_sdf(self):
""" Converts the 2D image to a 2D signed distance field.
Returns
-------
:obj:`numpy.ndarray`
2D float array of the signed distance field
"""
# compute medial axis transform
skel, sdf_in = morph.medial_axis(self.data, return_distance=True)
useless_skel, sdf_out = morph.medial_axis(
np.iinfo(np.uint8).max - self.data, return_distance=True)
# convert to true sdf
sdf = sdf_out - sdf_in
return sdf
python类medial_axis()的实例源码
def execute_Skeleton(proxy,obj):
from skimage.morphology import medial_axis
threshold=0.1*obj.threshold
try:
img2=obj.sourceObject.Proxy.img
img=img2.copy()
except:
sayexc()
img=cv2.imread(__dir__+'/icons/freek.png')
data = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Compute the medial axis (skeleton) and the distance transform
skel, distance = medial_axis(data, return_distance=True)
# Distance to the background for pixels of the skeleton
dist_on_skel = distance * skel
# entferne ganz duenne linien
dist_on_skelw =(dist_on_skel >= threshold)* distance
say("size of the image ...")
say(dist_on_skelw.shape)
# skel = np.array(dist_on_skelw,np.uint8)
skel = np.array(dist_on_skelw *255/np.max(dist_on_skelw),np.uint8)
obj.Proxy.img=cv2.cvtColor(skel*100, cv2.COLOR_GRAY2BGR)
obj.Proxy.dist_on_skel=dist_on_skelw
def place_routers_on_skeleton(d, cmethod):
wireless = np.where(d["graph"] == Cell.Wireless, 1, 0)
# perform skeletonization
skeleton = skeletonize(wireless)
med_axis = medial_axis(wireless)
skel = skeleton
# skel = med_axis
# get all skeleton positions
pos = []
for i in range(skel.shape[0]):
for j in range(skel.shape[1]):
if skel[i][j]:
pos.append((i, j))
budget = d['budget']
shuffle(pos)
max_num_routers = min([int(d['budget'] / d['price_router']), len(pos)])
print("Num of routers constrained by:")
print(" budget: %d" % int(int(d['budget'] / d['price_router'])))
print(" skeleton: %d" % len(pos))
for i in tqdm(range(max_num_routers), desc="Placing Routers"):
new_router = pos[i]
a, b = new_router
# check if remaining budget is enough
d["graph"][a][b] = Cell.Router
d, ret, cost = _add_cabel(d, new_router, budget)
budget -= cost
if not ret:
break
return d
def place_routers_on_skeleton_iterative(d, cmethod):
budget = d['budget']
R = d['radius']
max_num_routers = int(d['budget'] / d['price_router'])
coverage = np.where(d["graph"] == Cell.Wireless, 1, 0).astype(np.bool)
pbar = tqdm(range(max_num_routers), desc="Placing Routers")
while budget > 0:
# perform skeletonization
# skeleton = skeletonize(coverage)
skeleton = medial_axis(coverage)
# get all skeleton positions
pos = np.argwhere(skeleton > 0).tolist()
# escape if no positions left
if not len(pos):
break
# get a random position
shuffle(pos)
a, b = pos[0]
# place router
d["graph"][a][b] = Cell.Router
d, ret, cost = _add_cabel(d, (a, b), budget)
if not ret:
print("No budget available!")
break
budget -= cost
# refresh wireless map by removing new coverage
m = wireless_access(a, b, R, d['graph']).astype(np.bool)
coverage[(a - R):(a + R + 1), (b - R):(b + R + 1)] &= ~m
pbar.update()
pbar.close()
return d
def medial_axis(data, idx, branch = True):
h, w = data.shape
data = data.ravel()
for id in idx:
if data[id]==0:continue
i2=id-w;i8=id+w;i1=i2-1;i3=i2+1;
i4=id-1;i6=id+1;i7=i8-1;i9=i8+1;
c = (data[i1]>0)<<0|(data[i2]>0)<<1\
|(data[i3]>0)<<2|(data[i4]>0)<<3\
|(data[i6]>0)<<4|(data[i7]>0)<<5\
|(data[i8]>0)<<6|(data[i9]>0)<<7
if (lut[c//8]>> c%8) &1:data[id]=0
return 0;
def mid_axis(img):
dis = ndimg.distance_transform_edt(img)
idx = np.argsort(dis.flat).astype(np.int32)
medial_axis(dis, idx, lut)
return dis
def execute_FatColor(proxy,obj):
import matplotlib.pyplot as plt
from skimage.morphology import medial_axis
try:
img2=obj.sourceObject.Proxy.img
img=img2.copy()
except:
sayexc()
img=cv2.imread(__dir__+'/icons/freek.png')
lower = np.array([255,255,255])
upper = np.array([255,255,255])
mask = cv2.inRange(img, lower, upper)
res = cv2.bitwise_and(img,img, mask= mask)
ks=3
kernel = np.ones((ks,ks),np.uint8)
kernelPLUS=np.array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype=np.uint8)
kernelCROSS=np.array([[1, 0,1],
[0, 1, 0],
[1, 0, 1]], dtype=np.uint8)
dilation = cv2.dilate(res,kernel,iterations = 1)
erode1 = cv2.erode(res,kernelPLUS,iterations = 1)
erode2 = cv2.erode(res,kernelCROSS,iterations = 1)
erode = cv2.erode(res,kernel,iterations = 1)
res=dilation
res=erode1 + erode2
dilation = cv2.dilate(res,kernel,iterations = 1)
res=dilation
# plt.imshow(res, cmap=plt.cm.PRGn, interpolation='nearest')
# plt.show()
obj.Proxy.img=res
#---------------------------------
def skeletonize_image(image, method=None, dilation=None, binarization=None,
invert=False):
"""Extract a 1 pixel wide representation of image by morphologically
thinning the white contiguous blobs (connected components).
If image is not black and white, a binarization process is applied
according to binarization, which can be 'sauvola', 'isodata', 'otsu',
'li' (default, ref: binarize()).
A process of dilation can also be applied by specifying the number
of pixels in dilate prior to extracting the skeleton.
The method for skeletonization can be 'medial', '3d', 'regular', or a
'combined' version of the three. Defaults to 'regular'.
A 'thin' operator is also available. For reference,
see http://scikit-image.org/docs/dev/auto_examples/edges/plot_skeleton.html
"""
# if image is all one single color, return it
if len(np.unique(image)) == 1:
return image
# scikit-image needs only 0's and 1's
mono_image = binarize_image(image, method=binarization) / 255
if invert:
mono_image = invert_image(mono_image)
if dilation:
dilation = (2 * dilation) + 1
dilation_kernel = np.ones((dilation, dilation), np.uint8)
mono_image = cv2.morphologyEx(mono_image, cv2.MORPH_DILATE,
dilation_kernel)
with warnings.catch_warnings(record=True):
warnings.filterwarnings('ignore', category=UserWarning)
if method == '3d':
skeleton = morphology.skeletonize_3d(mono_image)
elif method == 'medial':
skeleton = morphology.medial_axis(mono_image,
return_distance=False)
elif method == 'thin':
skeleton = morphology.thin(mono_image)
elif method == 'combined':
skeleton = (morphology.skeletonize_3d(mono_image)
| morphology.medial_axis(mono_image,
return_distance=False)
| morphology.skeletonize(mono_image))
else:
skeleton = morphology.skeletonize(mono_image)
return convert(skeleton)