简体   繁体   English

numpy:将值分配给带有索引列表的2d数组

[英]Numpy: assigning values to 2d array with list of indices

I have 2d numpy array (think greyscale image). 我有2d的numpy数组(想想灰度图像)。 I want to assign certain value to a list of coordinates to this array, such that: 我想为该数组的坐标列表分配某些值,例如:

img = np.zeros((5, 5))
coords = np.array([[0, 1], [1, 2], [2, 3], [3, 4]]) 

def bad_use_of_numpy(img, coords):
    for i, coord in enumerate(coords):
        img[coord[0], coord[1]] = 255

    return img

bad_use_of_numpy(img, coords)

This works, but I feel like I can take advantage of numpy functionality to make it faster. 这行得通,但是我觉得我可以利用numpy功能来使其更快。 I also might have a use case later to to something like following: 以后我可能还会有一个用例,如下所示:

img = np.zeros((5, 5))
coords = np.array([[0, 1], [1, 2], [2, 3], [3, 4]])
vals = np.array([1, 2, 3, 4])

def bad_use_of_numpy(img, coords, vals):
    for coord in coords:
        img[coord[0], coord[1]] = vals[i]

    return img

 bad_use_of_numpy(img, coords, vals)

Is there a more vectorized way of doing that? 有更矢量化的方法吗?

We can unpack each row of coords as row, col indices for indexing into img and then assign. 我们可以将coords每一行解包为行,然后将col索引解包以索引到img ,然后进行分配。

Now, since the question is tagged : Python 3.x , on it we can simply unpack with [*coords.T] and then assign - 现在,由于问题被标记为: Python 3.x ,我们可以简单地用[*coords.T]解压缩,然后分配-

img[[*coords.T]] = 255

Generically, we can use tuple to unpack - 通常,我们可以使用tuple来解包-

img[tuple(coords.T)] = 255

We can also compute the linear indices and then assign with np.put - 我们还可以计算线性索引,然后分配np.put

np.put(img, np.ravel_multi_index(coords.T, img.shape), 255)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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