scipy.ndimage.
generate_binary_structure#
- scipy.ndimage.generate_binary_structure(rank, connectivity)[原始碼]#
為二元形態學操作產生二元結構。
- 參數:
- rankint
結構化元素將應用於陣列的維度數量,由 np.ndim 回傳。
- connectivityint
connectivity 決定輸出陣列的哪些元素屬於該結構,亦即,被視為中心元素的鄰居。與中心距離平方小於等於 connectivity 的元素被視為鄰居。connectivity 的範圍可以從 1 (沒有對角線元素是鄰居) 到 rank (所有元素都是鄰居)。
- 回傳值:
- outputndarray of bools
可用於二元形態學操作的結構化元素,具有 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)