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

要將 func 應用於的 labels 子集。如果是純量,則會傳回單一值。如果為 None,則 func 會應用於 labels 的所有非零值。

func可呼叫物件

要從 input 應用於 labels 的 Python 函數。

out_dtypedtype

用於 result 的 Dtype。

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