2016-04-21 55 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]