需要找到在多个线段上迭代的两条线段的交点

2024-04-25 06:54:10 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,问题出在这里。我试图通过比较从一系列csv文件中读取的多个线段来计算两条直线的交点。我已经将每个线段的x,y坐标对放入元组中的元组列表中,如下所示:

continuousLine = [((x1,y1),(x2,y2)), ...]
crossingLines = [((x1,y1),(x2,y2)), ...]

Line Problem

我想知道如何沿着连续的线迭代,穿过交叉线,找出沿着这条连续线每一条交叉线相交的地方。在

基本上我想要(下面列出的伪代码):

^{pr2}$

我不喜欢在这方面寻求帮助,因为我对编码太陌生,无法帮助其他人,但希望有人能和我一起解决这个问题。在

我确实有一种方法,我想一旦我找到迭代器,它就能计算出交集:

line1 = ()
line2 = ()
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]) #Typo was here

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(xdiff, ydiff)
    if div == 0:
       raise Exception('lines do not intersect')

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

print line_intersection((A, B), (C, D))

Tags: divdefline交叉元组x1x2det
2条回答

假设函数line_intersection将对div == 0返回False,而不是引发execption。在

简单方法:

filter(None, [intersection(a, b) for a in continuousLine for b in crossingLines])

然而,使用嵌套循环时,当交叉线中有许多线段时,它的速度很慢。在

更有效的方法:

为了提高性能,请尝试一下intervaltree,这将为您提供用于测试的intersect候选。在您的例子中,首先在交叉线上构建一个间隔树,然后在连续线中循环以在该树中找到相交候选对象,并进行测试以获得最终结果。在

由于您没有提供任何示例输入和预期输出,所以我将使用下面所示的line_intersection()函数的虚拟版本。它所做的只是打印输入并返回一个硬编码的结果-但是它将向您展示如何迭代输入数据并将其传递给实函数。在

从输出中应该可以清楚地看到它在做什么。在

def line_intersection(line1, line2):
    print('intersecting:')
    print('  ({}. {}), ({}, {})'.format(line1[0][0], line1[0][1],
                                        line1[1][0], line1[1][1]))
    print('  ({}. {}), ({}, {})'.format(line2[0][0], line2[0][1],
                                        line2[1][0], line2[1][1]))
    print('')
    return 100, 200

所有的循环都放在一个名为find_intersections()的生成器函数中,该函数返回它找到的连续交集,并跳过任何没有找到的组合

^{pr2}$

下面是一个使用虚构输入数据的用法示例:

continuous_line = [((1,2),(3,4)), ((5,6),(7,8)), ((9,10),(11,12))]
crossing_lines = [((21,22),(23,24)), ((25,26),(27,28)), ((29,30),(31,32))]
intersections = [(x, y) for x, y in
                    find_intersections(continuous_line, crossing_lines)]
print('intersections found:')
print(intersections)

输出:

intersecting:
  (1. 2), (3, 4)
  (21. 22), (23, 24)

intersecting:
  (1. 2), (3, 4)
  (25. 26), (27, 28)

intersecting:
  (1. 2), (3, 4)
  (29. 30), (31, 32)

intersecting:
  (5. 6), (7, 8)
  (21. 22), (23, 24)

intersecting:
  (5. 6), (7, 8)
  (25. 26), (27, 28)

intersecting:
  (5. 6), (7, 8)
  (29. 30), (31, 32)

intersecting:
  (9. 10), (11, 12)
  (21. 22), (23, 24)

intersecting:
  (9. 10), (11, 12)
  (25. 26), (27, 28)

intersecting:
  (9. 10), (11, 12)
  (29. 30), (31, 32)

intersections found:
[(100, 200), (100, 200), (100, 200), (100, 200), (100, 200), (100, 200), (100,
200), (100, 200), (100, 200)]

相关问题 更多 >