Python判断线段相交和图形相交

# 创建图形之间每个点之间的线段(点必须按顺序,不能交叉)
def create_line_list(shape):
    line_list = []  # [[[1,2],[3,4]],....]
    for i in range(len(shape)):
        if i == len(shape) - 1:
            line = [shape[i], shape[0]]
            line_list.append(line)
            return line_list
        else:
            line = [shape[i], shape[i + 1]]
            line_list.append(line)


# 判断两线段是否相交
def line_cross(l1, l2):
    """
    :param l1: line 1 [p1,p2]  p =[[x1,y1],[x2,y2]]
    :param l2: line 2 [p1,p2]
    :return: BOOL
    """
    if not l1[0][0] - l1[1][0]:  # 垂线l1
        x1 = l1[0][0]
    else:  # 斜线l1
        k1 = (l1[0][1] - l1[1][1]) / (l1[0][0] - l1[1][0])
        b1 = l1[0][1] - k1 * l1[0][0]
    if not l2[0][0] - l2[1][0]:  # 垂线l2
        x2 = l2[0][0]
    else:  # 斜线l2
        k2 = (l2[0][1] - l2[1][1]) / (l2[0][0] - l2[1][0])
        b2 = l2[0][1] - k2 * l2[0][0]
    # 平行线
    if not l2[0][0] - l2[1][0] and not l1[0][0] - l1[1][0]:
        return False
    if l2[0][0] - l2[1][0] and l1[0][0] - l1[1][0]:
        if k1 == k2:
            return False

    # 直线交点
    if not l1[0][0] - l1[1][0] and l2[0][0] - l2[1][0]:
        y = x1 * k2 + b2
        if k2 == 0 and min(l1[0][1], l1[1][1]) <= y <= max(l1[0][1], l1[1][1]) and min(l2[0][0], l2[1][0]) <= x1 <= max(l2[0][0], l2[1][0]):
            return True
    elif not l2[0][0] - l2[1][0] and l1[0][0] - l1[1][0]:
        y = x2 * k1 + b1
        if k1 == 0 and min(l2[0][1], l2[1][1]) <= y <= max(l2[0][1], l2[1][1]) and min(l1[0][0], l1[1][0]) <= x2 <= max(l1[0][0], l1[1][0]):
            return True
    else:
        x = round((b1 - b2) / (k2 - k1), 2)
        y = x * k1 + b1
    # 判断交点位置
    if min(l1[0][1], l1[1][1]) < y < max(l1[0][1], l1[1][1]) and min(l2[0][1], l2[1][1]) < y < max(l2[0][1],
                                                                                                   l2[1][1]):
        print(l1, l2)
        return True

    return False

# 判断图形相交(两图形中的每个线段判断相交)
def shape_cross(shape1, shape2):
    shape1_line_list = create_line_list(shape1)
    shape2_line_list = create_line_list(shape2)
    res = False
    for line1 in shape1_line_list:
        for line2 in shape2_line_list:
            res = line_cross(line1, line2)
            if res:
                return res
    return res


if __name__ == '__main__':
    s1 = np.array([[1, 2], [2, 4], [5, 6], [1, 7]])
    s2 = np.array([[0, 1], [3, 6]])
    print(shape_cross(s2, s1))
    pass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值