![](/img/trans.png)
[英]Vectorized way of adding to an array that is indexed by another array - Python/NumPy
[英]Fast way to recolour an indexed image based on another array
我有一个包含多个区域的索引图像bins
。 0
是背景,其他正值是区域。
我想基于另一个数组为每个区域填写值,例如:
bins = # image of shape (height, width), type int
ids = np.array([1, 5, ... ]) # region ids
values = np.array([0.1, ...]) # Values for each region, same shape as ids
img = np.empty(bins.shape, 'float32')
img[:] = np.nan
for i, val in zip(ids, values):
img[bins == i + 1] = val
但是这个循环在python中超级慢。 有没有办法以一种很好的numpy方式编写它?
提前致谢!
这是一种方法-
out = np.take(values, np.searchsorted(ids, bins-1))
out.ravel()[~np.in1d(bins,ids+1)] = np.nan
请注意,这假定要对ids
进行排序。 如果不是这种情况,我们需要使用可选参数sorter
与np.searchsorted
。
这是另一个想法非常相似的np.searchsorted
,但是作为一个较小的调整,它使用初始化并仅在有效元素上限制了对np.searchsorted
的使用-
out = np.full(bins.shape, np.nan)
mask = np.in1d(bins,ids+1)
out.ravel()[mask] = np.take(values, np.searchsorted(ids+1, bins.ravel()[mask]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.