numpy - Python - Apply a function over a labeled multidimensional array -
i have numpy
array labelled using scipy
connected component labelling.
import numpy scipy import ndimage = 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 apply custom function (calculation of specific value) on labels within labelled array. similar instance ndimage algebra functions:
ndimage.sum(a,lbl,range(1,numpatches+1))
( in case returns me number of values each label [6,6]
. )
is there way this?
you can pass arbitrary function ndimage.labeled_comprehension
, equivalent
[func(a[lbl == i]) in index]
here labeled_comprehension
-equivalent of ndimage.sum(a,lbl,range(1,numpatches+1))
:
import numpy np scipy import ndimage = 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]
Comments
Post a Comment