我想在我的 numpy 矩阵中的一个点的范围 1(或恰好对角线)内找到一个点列表:
例如说我的矩阵 m
是:
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 1 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
我想获得一个元组列表或表示以下 X 的 9 个点的所有坐标的东西:
[[0 0 0 0 0]
[0 X X X 0]
[0 X X X 0]
[0 X X X 0]
[0 0 0 0 0]]
这是目标点在边缘的另一个例子:
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 1]
[0 0 0 0 0]
[0 0 0 0 0]]
在这种情况下,目标点的距离 1 内只有 6 个点:
[[0 0 0 0 0]
[0 0 0 X X]
[0 0 0 X X]
[0 0 0 X X]
[0 0 0 0 0]]
编辑:
假设我知道目标点的坐标,这里使用 David Herrings 关于切比雪夫距离的回答/评论是我尝试解决上面示例 2 的尝试:
from scipy.spatial import distance
point = [2, 4]
valid_points = []
for x in range(5):
for y in range(5):
if(distance.chebyshev(point, [x,y]) <= 1):
valid_points.append([x,y])
print(valid_points) # [[1, 3], [1, 4], [2, 3], [2, 4], [3, 3], [3, 4]]
对于更大的数组,这似乎有点低效,因为我只需要检查一小组单元格,而不是整个矩阵。
最佳答案
我觉得你让它有点太复杂了——不需要依赖复杂的函数
import numpy as np
# set up matrix
x = np.zeros((5,5))
# add a single point
x[2,-1] = 1
# get coordinates of point as array
r, c = np.where(x)
# convert to python scalars
r = r[0]
c = c[0]
# get boundaries of array
m, n = x.shape
coords = []
# loop over possible locations
for i in [-1, 0, 1]:
for j in [-1, 0, 1]:
# check if location is within boundary
if 0 <= r + i < m and 0 <= c + j < n:
coords.append((r + i, c + j))
print(coords)
>>> [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
关于python - 在 2D numpy 矩阵中查找特定点距离 1 内的所有点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52920499/