scipy.ndimage.
generate_binary_structure#
- scipy.ndimage.generate_binary_structure(rank, connectivity)[源代码]#
生成用于二进制形态学操作的二值结构。
- 参数:
- rankint
结构元素将应用于的数组的维数,由 np.ndim 返回。
- connectivityint
connectivity 确定输出数组的哪些元素属于该结构,即被视为中心元素的邻居。从中心到 connectivity 的平方距离内的元素被视为邻居。connectivity 可以从 1(没有对角元素是邻居)到 rank(所有元素都是邻居)。
- 返回:
- output布尔类型的 ndarray
可用于二进制形态学操作的结构元素,具有 rank 个维度,且所有维度都等于 3。
注意
generate_binary_structure
只能创建维度等于3的结构元素,即最小维度。对于更大的结构元素,例如用于侵蚀大型对象,可以使用iterate_structure
,或者直接使用 NumPy 函数(例如numpy.ones
)创建自定义数组。示例
>>> from scipy import ndimage >>> import numpy as np >>> struct = ndimage.generate_binary_structure(2, 1) >>> struct array([[False, True, False], [ True, True, True], [False, True, False]], dtype=bool) >>> a = np.zeros((5,5)) >>> a[2, 2] = 1 >>> a array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 1., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]]) >>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype) >>> b array([[ 0., 0., 0., 0., 0.], [ 0., 0., 1., 0., 0.], [ 0., 1., 1., 1., 0.], [ 0., 0., 1., 0., 0.], [ 0., 0., 0., 0., 0.]]) >>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype) array([[ 0., 0., 1., 0., 0.], [ 0., 1., 1., 1., 0.], [ 1., 1., 1., 1., 1.], [ 0., 1., 1., 1., 0.], [ 0., 0., 1., 0., 0.]]) >>> struct = ndimage.generate_binary_structure(2, 2) >>> struct array([[ True, True, True], [ True, True, True], [ True, True, True]], dtype=bool) >>> struct = ndimage.generate_binary_structure(3, 1) >>> struct # no diagonal elements array([[[False, False, False], [False, True, False], [False, False, False]], [[False, True, False], [ True, True, True], [False, True, False]], [[False, False, False], [False, True, False], [False, False, False]]], dtype=bool)