[英]Fast way to recolour an indexed image based on another array
I have a an indexed image bins
consisting of multiple regions. 我有一个包含多个区域的索引图像
bins
。 0
is background and other positive value is a region. 0
是背景,其他正值是区域。
I want to fill in values for each region based on another array, eg: 我想基于另一个数组为每个区域填写值,例如:
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
but this loop is super slow in python. 但是这个循环在python中超级慢。 Is there a way to write it in a nice numpy way?
有没有办法以一种很好的numpy方式编写它?
Thanks in advance! 提前致谢!
Here's an approach - 这是一种方法-
out = np.take(values, np.searchsorted(ids, bins-1))
out.ravel()[~np.in1d(bins,ids+1)] = np.nan
Please note that this assumes ids
to be sorted. 请注意,这假定要对
ids
进行排序。 If that's not the case, we need to use the optional argument sorter
with np.searchsorted
. 如果不是这种情况,我们需要使用可选参数
sorter
与np.searchsorted
。
Here's another one with a very similar idea, but as a minor tweak using initialization and limiting the use of np.searchsorted
only on the valid elements - 这是另一个想法非常相似的
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.