简体   繁体   English

快速着色基于另一个数组的索引图像的方法

[英]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 . 如果不是这种情况,我们需要使用可选参数sorternp.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.

相关问题 向另一个数组索引的数组添加向量化方法-Python / NumPy - Vectorized way of adding to an array that is indexed by another array - Python/NumPy 根据条件舍入数组值的快速方法 - Fast way to round array values based on condition 在numpy中更新整数索引切片的快速方法 - Fast way to update integer indexed slice in numpy 用与另一个数组的零相对应的零替换元素的快速方法 - Fast way to replace elements by zeros corresponding to zeros of another array 将加法向量化到另一个数组索引的数组中 - Vectorize addition into array indexed by another array 快速检查numpy数组的子维度中的元素是否在另一个numpy数组的子维度中的方法 - Fast way to check if elements in sub-dimension of a numpy array is in sub-dimension of another numpy array 2D Numpy 数组:基于标准列使用另一个数组快速更新行 - 2D Numpy array: very fast update of rows with another array based on criteria column 一种高效(快速)的方法,可以根据从Python Pandas中另一个DataFrame获取的范围将一个DataFrame中的连续数据分组? - Efficient (fast) way to group continuous data in one DataFrame based on ranges taken from another DataFrame in Python Pandas? 将3d numpy数组(RGB图像)转换为布尔数组的快速方法 - Fast way to convert 3d numpy array (RGB image) to a boolean array numpy:快速/简便的方法来获取值等于另一个数组的数组的索引? - Numpy: fast/easy way to get indices of array whose value is equal to another array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM