如果我在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/

10-12 17:15
查看更多