从numpy数组中获取坐标

3

也许这是关于numpy的一个基本问题,但我不知道该如何去做。我们假设有一个类似下面的2D numpy数组:

import numpy as np

arr = np.array([[  0., 460., 166., 167., 123.],
                [  0.,   0.,   0.,   0.,   0.],
                [  0.,  81.,   0.,  21.,   0.],
                [  0., 128.,  23.,   0.,  12.],
                [  0.,  36.,   0.,  13.,   0.]])

我需要从子数组中获取坐标。
[[0., 21,.  0.],
 [23., 0., 12.],
 [0., 13.,  0.]]

我尝试对原始数组进行切片,然后使用np.argwhere查找坐标,就像这样

newarr = np.argwhere(arr[2:, 2:] != 0)

#output
#[[0 1]
# [1 0]
# [1 2]
# [2 1]]

这些确实是子数组的坐标,但我期望的是对应于我的原始数组的坐标。期望的输出结果是:

[[2 3]
 [3 2]
 [3 4]
 [4 3]]

如果我使用np.argwhere和原始数组,我会得到一堆我不需要的坐标,所以我无法弄清楚如何获得我需要的内容,请帮助我或者指导我正确的方向,谢谢!
2个回答

3
假设矩阵的原点位于左上角,并且该矩阵位于笛卡尔空间的第四象限中。水平轴具有列索引,垂直轴向下具有行索引。
您将看到整个子矩阵在坐标(2,2)处进行了原点偏移。因此,当您得到的坐标是相对于原点的子矩阵时,要将它们返回到(2,2),只需在所有元素中添加(2,2)即可。
>>> np.argwhere(arr[2:, 2:] != 0) + [2, 2]
array([[2, 3],
       [3, 2],
       [3, 4],
       [4, 3]])

其他示例:

>>> col_shift, row_shift = 3, 2

>>> arr[row_shift:, col_shift:]
array([[21.,  0.],
       [ 0., 12.],
       [13.,  0.]])

>>> np.argwhere(arr[row_shift:, col_shift:] != 0) + [row_shift, col_shift]
array([[2, 3],
       [3, 4],
       [4, 3]])

对于完全内部的子矩阵,您可以限定列和行:

>>> col_shift, row_shift = 0, 1
>>> col_bound, row_bound = 4, 4

>>> arr[row_shift:row_bound, col_shift:col_bound]
array([[  0.,   0.,   0.,   0.],
       [  0.,  81.,   0.,  21.],
       [  0., 128.,  23.,   0.]])

>>> np.argwhere(arr[row_shift:row_bound, col_shift:col_bound] != 0) + [row_shift, col_shift]
array([[2, 1],
       [2, 3],
       [3, 1],
       [3, 2]])

1
哦,我明白你的意思了!谢谢! - Carlos Eduardo Corpus

0

你已经向下移动了数组两次,并向右移动了两次。现在你只需要将向X和向Y的步数相加,就可以得到坐标:

y = 2
x = 2

newarr = np.argwhere(arr[y:, x:] != 0)
X = (newarr[0:, 0] + x).reshape(4,1)
Y = (newarr[0:, 1] + y).reshape(4,1)
print(np.concatenate((X, Y), axis=1))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接