Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于另一数组的索引图像快速重采样方法_Python_Performance_Numpy_Vectorization - Fatal编程技术网

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