Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing numpy meshgrid points outside of a Shapely polygon

Tags:

numpy

shapely

I have a 10 x 10 grid that I would like to remove points outside of a shapely Polygon:

import numpy as np
from shapely.geometry import Polygon, Point
from descartes import PolygonPatch

gridX, gridY = np.mgrid[0.0:10.0, 0.0:10.0]
poly = Polygon([[1,1],[1,7],[7,7],[7,1]])

#plot original figure
fig = plt.figure()
ax = fig.add_subplot(111)
polyp = PolygonPatch(poly)
ax.add_patch(polyp)
ax.scatter(gridX,gridY)
plt.show()

Here is the resulting figure: original fig

And what I want the end result to look like: end

I know that I can reshape the array to a 100 x 2 array of grid points:

stacked = np.dstack([gridX,gridY])
reshaped = stacked.reshape(100,2)

I can see if the point lies within the polygon easily:

for i in reshaped:
    if Point(i).within(poly):
         print True

But I am having trouble taking this information and modifying the original grid

like image 711
camdenl Avatar asked Nov 02 '25 13:11

camdenl


1 Answers

You're pretty close already; instead of printing True, you could just append the points to a list.

output = []
for i in reshaped:
    if Point(i).within(poly):
        output.append(i)

output = np.array(output)
x, y = output[:, 0], output[:, 1]

It seems that Point.within doesn't consider points that lie on the edge of the polygon to be "within" it though.

like image 95
pseudocubic Avatar answered Nov 05 '25 14:11

pseudocubic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!