Search code examples
pythonpolygonbounding-boxintersect

Crop a polygon to a bounding box without losing box edge


I am trying to crop polygons to a box The function I got so far is:


import numpy as np

def crop_polygon(x, y, xmin, xmax, ymin, ymax):
    # Create a mask to identify points inside the bounding box
    mask = (x >= xmin) & (x <= xmax) & (y >= ymin) & (y <= ymax)

    # Find the indices of points that are inside the bounding box
    inside_indices = np.where(mask)[0]

    # Extract the coordinates of the points inside the bounding box
    cropped_x = x[inside_indices]
    cropped_y = y[inside_indices]

    return cropped_x, cropped_y


x=np.array([20,50,100,200,400,500,800,850,750,600,300,150,0])
y=np.array([100,120,80,140,130,110,100,99,20,10,30,40,10])
xmin=200
xmax=700
ymin=0
ymax=200
cropped_x, cropped_y = crop_polygon(x, y, xmin, xmax, ymin, ymax)
print("Cropped x:", cropped_x)
print("Cropped y:", cropped_y)


Result:

Cropped x: [200 400 500 600 300]
Cropped y: [140 130 110  10  30]

Purpose here is to cut the polygon along the x axes, as can be seen by xmin and xmax.

The problem here is, that I am losing the "edges" where the polygon intersects the bounds at x. Ideally I would insert a point at (xmin,y) and (xmax,y) or manyfold points as this needs to work for all kinds of polygons.

Does anyone have a good solution or library for this?


Solution

  • I found a good solution using this: Cannot make GeoDataFrame from Shapely Polygons: NotImplementedError: A polygon does not itself provide the array interface. Its rings do

    thanks for reading and the responses!