简体   繁体   中英

Fast way to recolour an indexed image based on another array

I have a an indexed image bins consisting of multiple regions. 0 is background and other positive value is a region.

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. Is there a way to write it in a nice numpy way?

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. If that's not the case, we need to use the optional argument sorter with 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 -

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM