ymo*_*eev 5 python numpy vectorization python-3.x
我有2d numpy数组(想想灰度图像).我想将特定值分配给此数组的坐标列表,以便:
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)
Run Code Online (Sandbox Code Playgroud)
这有效,但我觉得我可以利用numpy功能来加快速度.我稍后可能会有一个用例,如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
是否有更多的矢量化方式?
我们可以解压缩每行coords作为row,col索引以进行索引img,然后分配.
现在,因为问题被标记:Python 3.x,在它上面我们可以简单地解压缩[*coords.T]然后分配 -
img[[*coords.T]] = 255
Run Code Online (Sandbox Code Playgroud)
一般来说,我们可以tuple用来解包 -
img[tuple(coords.T)] = 255
Run Code Online (Sandbox Code Playgroud)
我们还可以计算线性指数,然后分配np.put-
np.put(img, np.ravel_multi_index(coords.T, img.shape), 255)
Run Code Online (Sandbox Code Playgroud)