将点映射到numpy数组

时间:2020-04-07 16:29:35

标签: python numpy graphics mapping drawing

这可能是一个简单的问题。

我想获取具有x,y直角坐标的点的numpy索引。我应该使用int()floor()ceil(),还是不使用它们?

numpy数组表示一个网格图,笛卡尔系统的(0,0)位置应位于numpy数组的中心。

我找到了一幅图像,显示了我的问题:

screenshot showing desired mapping of coordinate to grid

1 个答案:

答案 0 :(得分:0)

假设您是在5x5的笛卡尔平面中工作。您可能会决定像这样用numpy表示飞机:

>>> x = np.arange(-12,13)
>>> x.shape = (5,5)
>>> x
array([[-12, -11, -10,  -9,  -8],
       [ -7,  -6,  -5,  -4,  -3],
       [ -2,  -1,   0,   1,   2],
       [  3,   4,   5,   6,   7],
       [  8,   9,  10,  11,  12]])

但是您的问题是您的来源不位于(0,0):

>>> x[0,0]
-12

因为所有数组均从0开始。要“固定”索引引用,每当引用二维数组时,只需将数组索引偏移一维范围的一半即可。

>>> x[math.floor(0 - 5/2),math.floor(0 - 5/2)]
0

类似:

>>> x[math.floor(-2 - 5/2),math.floor(-2 - 5/2)]
-12

您可以像这样引用您的数组:

>>> for i in range(-2,3):
...     for j in range(-2,3):
...             ix = math.floor(i - 5/2)
...             jy = math.floor(j - 5/2)
...             x[ix,jy] = x[ix,jy] * 5
...             print("{0:>5}".format(x[ix,jy]),end="")
...     print()
...
  -60  -55  -50  -45  -40
  -35  -30  -25  -20  -15
  -10   -5    0    5   10
   15   20   25   30   35
   40   45   50   55   60

这显然是一个人为的例子。