如何计算两条线的交点? [英] How do I compute the intersection point of two lines?

查看:206
本文介绍了如何计算两条线的交点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两条相交的线.我知道这两行的端点.如何在Python中计算交点?

I have two lines that intersect at a point. I know the endpoints of the two lines. How do I compute the intersection point in Python?

# Given these endpoints
#line 1
A = [X, Y]
B = [X, Y]

#line 2
C = [X, Y]
D = [X, Y]

# Compute this:
point_of_intersection = [X, Y]

推荐答案

与其他建议不同,这很简短,并且不使用像numpy这样的外部库. (并不是说使用其他库是不好的……不需要,特别是对于这样一个简单的问题,这很好.)

Unlike other suggestions, this is short and doesn't use external libraries like numpy. (Not that using other libraries is bad...it's nice not need to, especially for such a simple problem.)

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:
       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))

仅供参考,我将使用元组而不是列表来表达您的观点.例如

And FYI, I would use tuples instead of lists for your points. E.g.

A = (X, Y)


最初有一个错字.由于@ zidik,2014年9月已修复.

这只是以下公式的Python音译,其中的行是( a1 a2 )和( b1 b2 ),并且交点为 p . (如果分母为零,则线没有唯一的交点.)

This is simply the Python transliteration of the following formula, where the lines are (a1, a2) and (b1, b2) and the intersection is p. (If the denominator is zero, the lines have no unique intersection.)

这篇关于如何计算两条线的交点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆