[英]Python - Apply a function over a labeled multidimensional array
I have a numpy
array that is labelled using scipy
connected component labelling.我有一个使用
scipy
连接组件标签标记的numpy
数组。
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)
I want to apply a custom function (calculation of a specific value) over all labels within the labelled array.我想对标记数组中的所有标签应用自定义函数(计算特定值)。 Similar as for instance the ndimage algebra functions:
类似于 ndimage 代数函数:
ndimage.sum(a,lbl,range(1,numpatches+1))
( Which in this case returns me the number of values for each label [6,6]
. ) (在这种情况下,它会返回每个标签
[6,6]
的值数。)
Is there a way to do this?有没有办法做到这一点?
You can pass an arbitrary function to ndimage.labeled_comprehension
, which is roughly equivalent to您可以将任意函数传递给
ndimage.labeled_comprehension
,大致相当于
[func(a[lbl == i]) for i in index]
Here is the labeled_comprehension
-equivalent of ndimage.sum(a,lbl,range(1,numpatches+1))
:这里是
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.