Python 基于另一数组的索引图像快速重采样方法
我有一个由多个区域组成的索引图像Python 基于另一数组的索引图像快速重采样方法,python,performance,numpy,vectorization,Python,Performance,Numpy,Vectorization,我有一个由多个区域组成的索引图像bin0为背景,其他正值为区域 我想根据另一个数组填写每个区域的值,例如: 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, 'fl
bin
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中非常慢。有没有一种方法可以把它写得很好
提前谢谢 这里有一个方法-
out = np.take(values, np.searchsorted(ids, bins-1))
out.ravel()[~np.in1d(bins,ids+1)] = np.nan
请注意,这假定要对ids
进行排序。如果不是这样,我们需要将可选参数sorter
与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]))