2016-04-21 52 views
2

我有一個使用scipy連接組件標籤標記的numpy數組。Python - 在標記的多維數組上應用函數

import numpy 
from scipy import ndimage 

a = numpy.zeros((8,8), dtype=numpy.int) 
a[1,1] = a[1,2] = a[2,1] = a[2,2] = a[3,1] = a[3,2] = 1 
a[5,5] = a[5,6] = a[6,5] = a[6,6] = a[7,5] = a[7,6] = 1 
lbl, numpatches = ndimage.label(a) 

我想對帶標籤的數組中的所有標籤應用自定義函數(計算特定值)。 作爲實例ndimage代數函數類似:

ndimage.sum(a,lbl,range(1,numpatches+1)) 

(在這種情況下返回我值的每個標籤[6,6]數。)

有沒有辦法做到這一點?

回答

2

可以傳遞的任意函數來ndimage.labeled_comprehension,這大致相當於

[func(a[lbl == i]) for i in index] 

這裏是labeled_comprehension換算的ndimage.sum(a,lbl,range(1,numpatches+1))

import numpy as np 
from scipy import ndimage 

a = np.zeros((8,8), dtype=np.int) 
a[1,1] = a[1,2] = a[2,1] = a[2,2] = a[3,1] = a[3,2] = 1 
a[5,5] = a[5,6] = a[6,5] = a[6,6] = a[7,5] = a[7,6] = 1 
lbl, numpatches = ndimage.label(a) 

def func(x): 
    return x.sum() 

print(ndimage.labeled_comprehension(a, lbl, index=range(1, numpatches+1), 
            func=func, out_dtype='float', default=None)) 
# [6 6]