【问题标题】:how can I construct a list of NumPy arrays from these two arrays?如何从这两个数组构造一个 NumPy 数组列表?
【发布时间】:2021-03-27 19:46:16
【问题描述】:

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

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 乘法,但我看不到。谢谢。

【问题讨论】:

    标签: python-3.x numpy python-camelot


    【解决方案1】:

    简短:

    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]]),...]
    

    【讨论】:

      【解决方案2】:

      首先,尝试为每个框生成 x 和 y 坐标。您将分别有 3 个用于 x 和 y 的坐标集。然后,计算上述 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

      【讨论】:

        猜你喜欢
        • 2015-09-11
        • 1970-01-01
        • 2011-03-10
        • 2019-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-22
        相关资源
        最近更新 更多