0

I have two arrays which are column and row values in PDF coordinate space:

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

Here's a visual:

enter image description here

I need to convert this into a list of numpy arrays, where each array is the boundary coordinates (four points that define the box). For example, a list of the lower left and upper right boxes would be

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

And so on for nine boxes. How can I achieve this? I would guess some kind of NumPy multiplication but I can't see it. Thank you.

Chuck
  • 1,061
  • 1
  • 20
  • 45

2 Answers2

2

Short and simple:

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

The output:

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

First, try generating the x and y coordinates for each box. You will have 3 coordinate sets for x and for y respectively. Then, compute the cartesian product of the said x and y coordinate sets.

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)

More info about cartesian product:

Cartesian product of sets

How to implement the cartesian product in numpy efficiently

akocz
  • 138
  • 6