[英]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.