Search code examples
pythonpolygonshapely

Stacking small polygons inside another bigger one


I have the following shapely pixel polygon

big_poly = Polygon([(94.5, 77.0),
                    (92.5, 53.0),
                    (87.5, 45.0),
                    (66.0, 20.5),
                    (9.0, 3.5),
                    (5.5, 6.0),
                    (4.5, 13.0),
                    (7.5, 26.0),
                    (6.5, 91.0),
                    (8.0, 92.5),
                    (16.0, 92.5),
                    (44.0, 86.5)])

I need to fill the big_poly with 4 by 6, pixel polygons, have them all fall within the border of the big one and parallel to its min axis (same rotation).

The solutions here sure were helpful thanks to @Georgy. So I was able to do the following:

enter image description here

with the following code:

b = building_poly.boundary
points = []
for x in range(int(np.floor(xmin)), int(np.ceil(xmax)), 4):
for y in range(int(np.floor(ymin)), int(np.ceil(ymax)), 6):
points.append((x, y))
points = MultiPoint(points)
result = points.intersection(building_poly)

And plotting the points in result, but now I need to create polygons from these points. How can I turn these points into rectangular polygons?

I also found this, but not sure how to make it fit my case.


Solution

  • Here is what we could do:

    1. Construct two arrays of X and Y coordinates based on the boundaries of the given polygon
    2. Construct a grid of rectangles covering completely the given polygon by iterating over the consecutive pairs of X and Y coordinates
    3. Filter out those rectangles that don't lie completely inside the polygon

    This is, most probably, not the most efficient solution, but it performs well for your case:

    dx = 4
    dy = 6
    xmin, ymin, xmax, ymax = big_poly.bounds
    xs = np.arange(np.floor(xmin), np.ceil(xmax) + 1, dx) 
    ys = np.arange(np.floor(ymin), np.ceil(ymax) + 1, dy)
    rectangles = (Polygon([(x_start, y_start), (x_end, y_start), 
                           (x_end, y_end), (x_start, y_end)])
                  for x_start, x_end in zip(xs, xs[1:])
                  for y_start, y_end in zip(ys, ys[1:]))
    rectangles = [rectangle for rectangle in rectangles 
                  if big_poly.contains(rectangle)]
    

    enter image description here