我有一个使用 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)
我想对带标签的数组中的所有标签应用自定义函数(计算特定值)。 类似于例如 ndimage 代数函数:
ndimage.sum(a,lbl,range(1,numpatches+1))
(在这种情况下返回每个标签 [6,6] 的值的数量。)
有办法吗?
请您参考如下方法:
可以将任意函数传递给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]
