我如何从这两个数组构造一个 NumPy 数组列表?

how can I construct a list of NumPy arrays from these two arrays?

我有两个数组,它们是 PDF 坐标中的列值和行值 space:

x = array([111, 303, 405, 513]
y = array([523, 546 , 569 , 603 ])

这是一张图片:

我需要将其转换为 numpy 数组列表,其中每个数组都是边界坐标(定义框的四个点)。例如,左下角和右上角框的列表将是

all_boxes =
    [array([[111, 523],
            [303, 523],
            [303, 546],
            [111, 546]], dtype=int64),
    array([[405, 569],
            [513, 569],
            [513, 603],
            [405, 603]], dtype=int64)]

九个盒子以此类推。我怎样才能做到这一点?我猜是某种 NumPy 乘法,但我看不到它。谢谢。

首先,尝试为每个框生成 x 和 y 坐标。您将分别为 x 和 y 设置 3 个坐标集。然后,计算所述x和y坐标集的笛卡尔积。

import numpy as np

x = array([111, 303, 405, 513]
y = array([523, 546 , 569 , 603 ])

# generate grid points
xs = np.repeat(x, 4)[2:-2].reshape(-1, 4)
xs = np.roll(xs, -1,  axis=1)
ys = np.repeat(y, 4)[2:-2].reshape(-1, 4)

# cartesian product
xx = np.tile(xs, ys.shape[0]).reshape(-1, 4)
yy = np.tile(ys.reshape(1,-1), xs.shape[0]).reshape(-1, 4)
boxes = np.hstack((xx, yy)).reshape(-1, 2, 4)

有关笛卡尔积的更多信息:

Cartesian product of sets

How to implement the cartesian product in numpy efficiently

简短:

import numpy as np
x = np.array([111, 303, 405, 513])
y = np.array([523, 546 , 569 , 603 ])

def coupler(lst): return [[c1,c2] for c1,c2 in zip(lst,lst[1:])]

x_couples,y_couples=coupler(x),coupler(y)

boxes=[]
for x1,x2 in x_couples:
    for y1,y2 in y_couples:
        boxes.append(np.array([[x1,y1],[x2,y1],[x2,y2],[x1,y2]]))

输出:

[array([[111, 523],
        [303, 523],
        [303, 546],
        [111, 546]]), 
array([[111, 546],
        [303, 546],
        [303, 569],
        [111, 569]]),...]