使用 Python 测试折线是否相交
Test if polylines intersects using Python
是否有一个简单的解决方案来测试两条折线是否相交,而不使用任何库?
比如
PL1 = ((-1, -1), (1, -1), (1, 2)), PL2 = ((0, 1), (2, 1))
PL1.intersect(PL2)
我只能找到具有两个点的直线的解决方案。
如评论中所述,您可以在多边形的所有组成线之间应用传统的线交点算法(this for example)。例如:
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)
是否有一个简单的解决方案来测试两条折线是否相交,而不使用任何库?
比如
PL1 = ((-1, -1), (1, -1), (1, 2)), PL2 = ((0, 1), (2, 1))
PL1.intersect(PL2)
我只能找到具有两个点的直线的解决方案。
如评论中所述,您可以在多边形的所有组成线之间应用传统的线交点算法(this for example)。例如:
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)