You can use scipy.ndimage.morphology.distance_transform_edt which finds the closest background point (value 0) with the smallest Euclidean distance to input pixels.
(您可以使用scipy.ndimage.morphology.distance_transform_edt查找与输入像素具有最小欧氏距离的最近背景点(值0)。)
from scipy import ndimage
import pprint
def nearest_zero(image):
" Finds closest background (zero) element for each element in image "
# Find closest zero elements in the inverted image (same as closest non-zero for image)
edt = ndimage.distance_transform_edt(image, return_indices=False)
# Create dictionary of indexes
return {(r,c):edt[r][c] for r in range(image.shape[0]) for c in range(image.shape[1]) if image[r][c]}
Example of Usage
(使用范例)
image = np.array(([0,50,75,15,0],
[2,0,111,10,15],
[0,112,25,110,115],
[0,10,110,115,0],
[15,12,115,0,0]))
d = nearest_zero(image)
pp = pprint.PrettyPrinter(indent=4)
print('Original Image')
print(image)
print('
Dictionary of Distances to closest background pixel for each non-background pixel')
pp.pprint(sorted(d.items(), key=lambda x: x[0]))
Output
(输出量)
Original Image
[[ 0 50 75 15 0]
[ 2 0 111 10 15]
[ 0 112 25 110 115]
[ 0 10 110 115 0]
[ 15 12 115 0 0]]
Dictionary of Distances to closest background pixel for each non-background pixel
[ ((0, 1), 1.0),
((0, 2), 1.4142135623730951),
((0, 3), 1.0),
((1, 0), 1.0),
((1, 2), 1.0),
((1, 3), 1.4142135623730951),
((1, 4), 1.0),
((2, 1), 1.0),
((2, 2), 1.4142135623730951),
((2, 3), 1.4142135623730951),
((2, 4), 1.0),
((3, 1), 1.0),
((3, 2), 1.4142135623730951),
((3, 3), 1.0),
((4, 0), 1.0),
((4, 1), 1.4142135623730951),
((4, 2), 1.0)]