gpt4 book ai didi

python - 网格化一个numpy数组

转载 作者:行者123 更新时间:2023-11-28 22:44:22 24 4
gpt4 key购买 nike

xx和yy对应9个矩形的顶点。如何获取每个矩形的 4 个坐标作为元组?

>>> import numpy as np
>>> xx, yy = np.mgrid[0:4, 10:14]
>>> xx
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
>>> yy
array([[10, 11, 12, 13],
[10, 11, 12, 13],
[10, 11, 12, 13],
[10, 11, 12, 13]])
>>> xx, yy = xx.ravel(), yy.ravel()
>>> xx
array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])
>>> yy
array([10, 11, 12, 13, 10, 11, 12, 13, 10, 11, 12, 13, 10, 11, 12, 13])
>>> lists = list(zip(xx, yy))
>>> lists
[(0, 10), (0, 11), (0, 12), (0, 13), (1, 10), (1, 11), (1, 12), (1, 13), (2, 10), (2, 11), (2, 12), (2, 13), (3, 10), (3, 11), (3, 12), (3, 13)]

第一个矩形的坐标为:

[(0, 10), (0, 11), (1, 11), (1, 10)].

同样,我想以“list of lists”的格式获取其他8个矩形的坐标。

矩形的坐标顺序并不重要。

首选 NumPy/SciPy 方法。

最佳答案

一种方式,不使用 mgrid:

x = np.arange(4)
y = np.arange(10, 14)
d = [[0,0],[0,1],[1,1],[1,0]] # define order to go around rectangle here

for ix in range(len(x) - 1):
for iy in range(len(y) - 1):
print [(x[ix + dx], y[iy + dy]) for dx, dy in d]

结果:

[(0, 10), (0, 11), (1, 11), (1, 10)]
[(0, 11), (0, 12), (1, 12), (1, 11)]
[(0, 12), (0, 13), (1, 13), (1, 12)]
[(1, 10), (1, 11), (2, 11), (2, 10)]
[(1, 11), (1, 12), (2, 12), (2, 11)]
[(1, 12), (1, 13), (2, 13), (2, 12)]
[(2, 10), (2, 11), (3, 11), (3, 10)]
[(2, 11), (2, 12), (3, 12), (3, 11)]
[(2, 12), (2, 13), (3, 13), (3, 12)]

如果你坚持只使用 numpy,你可以这样做:

xx, yy = np.mgrid[0:4, 10:14]
top = xx[:-1,1:]
bot = xx[1:,1:]
left = yy[1:,:-1]
right = yy[1:,1:]
np.column_stack(v.ravel()
for v in (top, left, top, right, bot, right, bot, left))

结果是一个单一的矩阵,但是列和你想要的元组完全一样:

array([[ 0, 10,  0, 11,  1, 11,  1, 10],
[ 0, 11, 0, 12, 1, 12, 1, 11],
[ 0, 12, 0, 13, 1, 13, 1, 12],
[ 1, 10, 1, 11, 2, 11, 2, 10],
[ 1, 11, 1, 12, 2, 12, 2, 11],
[ 1, 12, 1, 13, 2, 13, 2, 12],
[ 2, 10, 2, 11, 3, 11, 3, 10],
[ 2, 11, 2, 12, 3, 12, 3, 11],
[ 2, 12, 2, 13, 3, 13, 3, 12]])

关于python - 网格化一个numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29587617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com