使用Python测试多段线是否相交
有没有一个简单的解决方案来测试两条多段线是否相交,而不使用任何库 比如使用Python测试多段线是否相交,python,intersection,polyline,Python,Intersection,Polyline,有没有一个简单的解决方案来测试两条多段线是否相交,而不使用任何库 比如 PL1 = ((-1, -1), (1, -1), (1, 2)), PL2 = ((0, 1), (2, 1)) PL1.intersect(PL2) 我只能找到两点直线的解 如注释中所述,您可以在多边形的所有组件线之间应用线交点()的传统算法。例如: def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0
PL1 = ((-1, -1), (1, -1), (1, 2)), PL2 = ((0, 1), (2, 1))
PL1.intersect(PL2)
我只能找到两点直线的解 如注释中所述,您可以在多边形的所有组件线之间应用线交点()的传统算法。例如:
def line_intersection(line1, line2):
xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])
def det(a, b):
return a[0] * b[1] - a[1] * b[0]
div = det(xdiff, ydiff)
if div == 0:
return None
d = (det(*line1), det(*line2))
x = det(d, xdiff) / div
y = det(d, ydiff) / div
return x, y
def poly_intersection(poly1, poly2):
for i, p1_first_point in enumerate(poly1[:-1]):
p1_second_point = poly1[i + 1]
for j, p2_first_point in enumerate(poly2[:-1]):
p2_second_point = poly2[j + 1]
if line_intersection((p1_first_point, p1_second_point), (p2_first_point, p2_second_point)):
return True
return False
PL1 = ((-1, -1), (1, -1), (1, 2))
PL2 = ((0, 1), (2, 1))
print poly_intersection(PL1, PL2)
不使用任何库?!?为什么要重新发明轮子?我同意@tnknepp。顺便说一句,您的代码不起作用,因为您正在比较
PL1
和PL2
中是否存在完全相似的元组,另外,对于intersect
方法,您需要设置集合。您的多段线只是一系列具有两点的多条线。为什么不使用与两点线相同的技术检查所有线段的交点?除非你的多段线实际上是曲线。看看这篇文章,你可能会发现它很有用。谢谢。我不确定,非常简单,代码的最后一部分。我只需要绕着线走。