给定一个由零组成的 numpy 数组,假设
arr = np.zeros((5, 5))
和代表多边形顶点的索引数组,比方说
verts = np.array([[0, 2], [2, 0], [2, 4]])
1)优雅的做法是什么
for v in verts:
arr[v[0], v[1]] = 1
结果数组是
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.]])
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.]])
最佳答案
回答问题的第一部分: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
对于第二部分,一种适用于任意多边形的方法是使用 matplotlib.Path.contains_points
,如所述here :
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.]])
关于python - 如何用给定的索引/坐标填充 numpy 的零数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40335161/