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].

依次对任意函数(适用于类数组输入)应用于由 labelsindex 指定的 N 维图像数组的子集。可以选择将位置参数作为第二个参数提供给函数。

参数:
input类数组

从中选择 labels 以进行处理的数据。

labels类数组或 None

input 中对象的标签。如果不是 None,数组的形状必须与 input 相同。如果是 None,则 func 将应用于展平的 input

index整数、整数序列或 None

labels 的子集,func 将应用于此子集。如果是标量,则返回单个值。如果是 None,则 func 将应用于 labels 的所有非零值。

func可调用对象

要应用于 inputlabels 的 Python 函数。

out_dtype数据类型

用于 result 的数据类型。

default整数、浮点数或 None

index 中的元素在 labels 中不存在时的默认返回值。

pass_positions布尔值,可选

如果为 True,则将线性索引作为第二个参数传递给 func。默认为 False。

返回值:
resultndarray

func 应用于 indexinput 内的每个 labels 的结果。

示例

>>> 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.])