删除 Shapely 多边形外部的 numpy 网格点

问题描述 投票:0回答:2

我有一个 10 x 10 网格,我想删除形状多边形之外的点:

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

这是结果图: original fig

我希望最终结果是这样的: end

我知道我可以将数组重塑为 100 x 2 网格点数组:

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

我可以轻松查看该点是否位于多边形内:

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

但是我在获取这些信息并修改原始网格时遇到困难

numpy shapely
2个回答
3
投票

你已经很接近了;您可以将点附加到列表中,而不是打印 True。

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

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

似乎

Point.within
并不认为位于多边形边缘的点位于多边形“内部”。


0
投票

关于@pseudocubic答案,我想添加一个答案,您也可以在其中包含边界条件。该方法使用 shapely >> 触摸进行添加,而不是附加符合条件的点,排除不符合条件的点,最后删除两个维度的所有空点:

import numpy as np
from shapely.geometry import LineString, Polygon, Point

gridX, gridY = np.mgrid[0.0:10.0, 0.0:10.0]
poly = Polygon([[1,1],[1,7],[7,7],[7,1]])
stacked = np.dstack([gridX,gridY])
reshaped = stacked.reshape(100,2)
points = reshaped.tolist()
for i, point in enumerate(points):
        point_geom = Point([point])
        if not poly.contains(point_geom) and not poly.touches(point_geom): ## (x != x_min and x != x_max and y != y_min and y != y_max):  # second condition ensures within boundary
            points[i] = ([],[])  # Mark the point as None if it's outside the polygon

mod_points = [[coord for coord in point if coord] for point in points]  
mod_points = [point for point in mod_points if point is not None and point != []]

对于绘图,

#plot original points
fig = plt.figure()
ax = fig.add_subplot(111)
# Extract the x and y coordinates of polygon
poly_x, poly_y = poly.exterior.xy
ax.plot(poly_x, poly_y, c = "green")
#ploting modified points
ax.scatter(gridX,gridY)
mod_x, mod_y = zip(*mod_points)
ax.scatter(mod_x,mod_y , c = 'red')
plt.show()

points inside polygon

© www.soinside.com 2019 - 2024. All rights reserved.