应用一个函数,该函数将一个参数带入一个标记为ndimage的数组

时间:2017-05-19 20:38:55

标签: python numpy scipy ndimage

我有一个使用scipy.ndimage标记过的数组,我希望将每个元素乘以特定于其相应标签的因子。我认为我可以使用ndimage.labeled_comprehension,但是我似乎无法弄清楚如何将参数传递给函数。例如:

"word word, word, word,".gsub(',', ', ').squeeze(' ')
  #=> "word word, word, word, "

正如预期的那样,它会出现错误,因为a = np.random.random(9).reshape(3,3) lbls = np.repeat(np.arange(3),3).reshape(3,3) ndx = np.arange(0,lbls.max()+1) factors = np.random.randint(10,size=3) >>> lbls array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> ndx array([0, 1, 2]) >>> factors array([5, 4, 8]) def fn(a, x): return a*x >>> b = ndimage.labeled_comprehension(a, labels=lbls, index=ndx, func=fn, out_dtype=float, default=0) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/tgrant/anaconda/envs/python2/lib/python2.7/site-packages/scipy/ndimage/measurements.py", line 416, in labeled_comprehension do_map([input], temp) File "/Users/tgrant/anaconda/envs/python2/lib/python2.7/site-packages/scipy/ndimage/measurements.py", line 411, in do_map output[i] = func(*[inp[l:h] for inp in inputs]) TypeError: fn() takes exactly 2 arguments (1 given) 需要fn()以某种方式输入它。 labeled_comprehension能够做到吗?

1 个答案:

答案 0 :(得分:1)

索引因子,然后简单地与图像数组相乘 -

a*factors[lbls]

示例运行 -

In [483]: a    # image/data array
Out[483]: 
array([[ 0.10682998,  0.29631501,  0.08501469],
       [ 0.46944505,  0.88346229,  0.75672908],
       [ 0.11381292,  0.24096868,  0.86438641]])

In [484]: factors  # scaling factors
Out[484]: array([8, 1, 1])

In [485]: lbls  # labels
Out[485]: 
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2]])

In [486]: factors[lbls] # factors populated based on the labels
Out[486]: 
array([[8, 8, 8],
       [1, 1, 1],
       [1, 1, 1]])

In [487]: a*factors[lbls] # finally scale the image array
Out[487]: 
array([[ 0.85463981,  2.37052006,  0.68011752],
       [ 0.46944505,  0.88346229,  0.75672908],
       [ 0.11381292,  0.24096868,  0.86438641]])