如果我在 2D 平面上有一个矢量(一条由 2 个点组成的线),我如何确定它是否穿过多边形?
我知道我可以获取构成多边形的每条线,看看是否有任何相交,但有没有更好的方法?
我读过这篇文章 How can I determine whether a 2D Point is within a Polygon?这给了我一些想法来查看该点是否在多边形内,但我需要查看它是否已经通过/与它相交。
最佳答案
如果你想要一个用于几何操作的 python 库,请查看 shapely
.它使这变得像 someline.intersects(somepolygon)
一样简单。
这是一个关于交集、缓冲区和裁剪的简单示例(有一个漂亮的图......我正在使用 descartes
轻松地将形状优美的多边形转换为 matplotlib 补丁。)。
import numpy as np
import matplotlib.pyplot as plt
import shapely.geometry
import descartes
circle = shapely.geometry.Point(5.0, 0.0).buffer(10.0)
clip_poly = shapely.geometry.Polygon([[-9.5, -2], [2, 2], [3, 4], [-1, 3]])
clipped_shape = circle.difference(clip_poly)
line = shapely.geometry.LineString([[-10, -5], [15, 5]])
line2 = shapely.geometry.LineString([[-10, -5], [-5, 0], [2, 3]])
print 'Blue line intersects clipped shape:', line.intersects(clipped_shape)
print 'Green line intersects clipped shape:', line2.intersects(clipped_shape)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(*np.array(line).T, color='blue', linewidth=3, solid_capstyle='round')
ax.plot(*np.array(line2).T, color='green', linewidth=3, solid_capstyle='round')
ax.add_patch(descartes.PolygonPatch(clipped_shape, fc='blue', alpha=0.5))
ax.axis('equal')
plt.show()
这会产生:
Blue line intersects clipped shape: True
Green line intersects clipped shape: False
关于python - 确定线段是否与多边形相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6050392/