求两个线段的交点,[线段,不是直线,不可无限延长]

# -*- coding: utf-8 -*-#
class Point:
    def __init__(self, xy):
        self.x = xy[0]
        self.y = xy[1]


def line_intersection(line1, line2):
    """
    :param line1: 线段一开头结尾坐标[[x1,y1], [x2,y2]]
    :param line2: 线段二开头结尾坐标[[x3,y3], [x4,y4]]
    :return: False/[x,y]
    """
    a, b, c, d = Point(line1[0]), Point(line1[1]), Point(line2[0]), Point(line1[1])
    # 三角形abc 面积的2倍
    area_abc = (a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x)
    # 三角形abd 面积的2倍
    area_abd = (a.x - d.x) * (b.y - d.y) - (a.y - d.y) * (b.x - d.x)
    # 面积符号相同则两点在线段同侧, 不相交(对点在线段上的情况, 本例当作不相交处理);
    if area_abc * area_abd >= 0:
        return False
    # 三角形cda面积的2倍
    area_cda = (c.x - a.x) * (d.y - a.y) - (c.y - a.y) * (d.x - a.x)
    # 三角形cdb面积的2倍
    # 注意: 这里有一个小优化.不需要再用公式计算面积, 而是通过已知的三个面积加减得出.
    area_cdb = area_cda + area_abc - area_abd
    if area_cda * area_cdb >= 0:
        return False
    # 计算交点坐标
    t = area_cda / (area_abd - area_abc)
    dx = t * (b.x - a.x)
    dy = t * (b.y - a.y)
    return [a.x + dx, a.y + dy]


if __name__ == '__main__':
    line_1 = [[0, 0], [5, 5]]
    line_2 = [[4, 1], [5, 0]]
    print(line_intersection(line_1, line_2))
posted @ 2022-09-27 15:55  不能说的秘密  阅读(238)  评论(0编辑  收藏  举报