scipy.ndimage.
labeled_comprehension#
- scipy.ndimage.labeled_comprehension(input, labels, index, func, out_dtype, default, pass_positions=False)[源代码][源代码]#
大致相当于 [func(input[labels == i]) for i in index]。
按顺序将任意函数(适用于类似数组的输入)应用于由 labels 和 index 指定的 N-D 图像数组的子集。可以选择将位置参数作为第二个参数提供给函数。
- 参数:
- 输入array_like
从中选择 标签 进行处理的数据。
- 标签类数组或无
input 中对象的标签。如果不是 None,数组必须与 input 形状相同。如果是 None,func 应用于展平的 input。
- 索引int, int序列或None
要应用 func 的 labels 子集。如果是标量,则返回单个值。如果为 None,则 func 应用于 labels 中所有非零值。
- 函数可调用
应用于 input 中 labels 的 Python 函数。
- out_dtypedtype
用于 result 的数据类型。
- 默认int, float 或 None
当 index 中的元素在 labels 中不存在时的默认返回值。
- 传递位置bool, 可选
如果为 True,将线性索引作为第二个参数传递给 func。默认为 False。
- 返回:
- 结果ndarray
在 index 中将 func 应用于 labels 到 input 的结果。
示例
>>> import numpy as np >>> a = np.array([[1, 2, 0, 0], ... [5, 3, 0, 4], ... [0, 0, 0, 7], ... [9, 3, 0, 0]]) >>> from scipy import ndimage >>> lbl, nlbl = ndimage.label(a) >>> lbls = np.arange(1, nlbl+1) >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0) array([ 2.75, 5.5 , 6. ])
回退到 default:
>>> lbls = np.arange(1, nlbl+2) >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1) array([ 2.75, 5.5 , 6. , -1. ])
传递位置:
>>> def fn(val, pos): ... print("fn says: %s : %s" % (val, pos)) ... return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum()) ... >>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True) fn says: [1 2 5 3] : [0 1 4 5] fn says: [4 7] : [ 7 11] fn says: [9 3] : [12 13] array([ 11., 11., -12., 0.])