如何用给定的索引/坐标填充零的numpy数组

lan*_*ery 5 python numpy scipy

给定一个零的numpy数组,说

arr = np.zeros((5, 5))
Run Code Online (Sandbox Code Playgroud)

以及代表多边形顶点的索引数组,例如

verts = np.array([[0, 2], [2, 0], [2, 4]])
Run Code Online (Sandbox Code Playgroud)

1)什么是优雅的做事方式

for v in verts:
    arr[v[0], v[1]] = 1
Run Code Online (Sandbox Code Playgroud)

这样结果数组是

In [108]: arr
Out[108]: 
array([[ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
Run Code Online (Sandbox Code Playgroud)

2)我如何用一个数组填充,以便输出数组是

In [158]: arr
Out[158]: 
array([[ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
Run Code Online (Sandbox Code Playgroud)

ali*_*i_m 5

要回答问题的第一部分: arr[tuple(verts.T)] = 1

verts.T将索引转置为(2, n)数组,其中两行对应于的行和列尺寸arr。然后将它们解压缩为一个元组(row_indices, col_indices),然后我们将其用作索引arr

我们可以更详细地写为:

row_indices = verts[:, 0]
col_indices = verts[:, 1]
arr[row_indices, col_indices] = 1
Run Code Online (Sandbox Code Playgroud)

对于第二部分,一个方法,将任意多边形的工作是使用matplotlib.Path.contains_points,如描述在这里

from matplotlib.path import Path

points = np.indices(arr.shape).reshape(2, -1).T
path = Path(verts)
mask = path.contains_points(points, radius=1e-9)
mask = mask.reshape(arr.shape).astype(arr.dtype)

print(repr(mask))
# array([[ 0.,  0.,  1.,  0.,  0.],
#        [ 0.,  1.,  1.,  1.,  0.],
#        [ 1.,  1.,  1.,  1.,  1.],
#        [ 0.,  0.,  0.,  0.,  0.],
#        [ 0.,  0.,  0.,  0.,  0.]])
Run Code Online (Sandbox Code Playgroud)