Home > front end >  Use numpy to find polygons in array of polygons which have at least one point in a bounding box
Use numpy to find polygons in array of polygons which have at least one point in a bounding box

Time:07-05

I have a numpy array of vertices for polygons. For example, a polygon could look like this:

np.array([(0, 0), (1, 3), (5, 7), (0, 9), (-1, 3)])

I have a list of polygons, for example:

np.array([[(0, 0), (1, 3), (5, 7), (0, 9), (-1, 3)], [(200, 200), (200, 300), (300, 300), (300, 200)], [(-10, -10), (-20, 5), (3, 2), (60, 8)]])

How would I filter this numpy array so that I am given only polygons that have at least one point in a certain bounding box, e.g. from (0, 0) to (10, 10)? This would rule out the second polygon, as all the points are larger than (10, 10). The first and third stay, because although both have points NOT in this range, they both have at least one that is.

How would I use numpy in this way to rapidly filter which polygons contain at least one vertex that is in a boudning box, ideally without converting it to a list and manually itterating?

CodePudding user response:

Defining the data:

import numpy as np

upper_limit= (10, 10)
lower_limit= (0, 0)
polygons = np.array([
               [(0, 0), (1, 3), (5, 7), (0, 9), (-1, 3)], 
               [(200, 200), (200, 300), (300, 300), (300, 200)], 
               [(-10, -10), (-20, 5), (3, 2), (60, 8)]
           ])

Defining the filter:

filter = [
          any([(lower_limit<= point <= upper_limit) 
          for point in polygon]) for polygon in polygons
]

The any function checks if at least one value is True in the list [(lower_limit<= point <= upper_limit) for point in polygon], which is a boolean list that checks if the polygon's points are inside the defined square.

The filter is another boolean list: [True, False, True] which has the polygons that have at least 1 point inside the defined square.

Result:

result = polygons[filter]
print(result)

[list([(0, 0), (1, 3), (5, 7), (0, 9), (-1, 3)])
 list([(-10, -10), (-20, 5), (3, 2), (60, 8)])]
  • Related