簡體   English   中英

快速着色基於另一個數組的索引圖像的方法

[英]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進行排序。 如果不是這種情況,我們需要使用可選參數sorternp.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM