首页 > 解决方案 > 如何使用python证明两条线段在autocad中是否相交

问题描述

如果有两条线段(不是线),我怎么知道它们是否被 python 相交?线方程定义了这些线段相交,即使它们不相互接触,因为方程无限地延伸线。

例子

段是否相互到达,下面的代码返回“相交”。

def intersection(s1, s2):
    segment_endpoints = []
    left = max(min(s1[0], s1[2]), min(s2[0], s2[2]))
    right = min(max(s1[0], s1[2]), max(s2[0], s2[2]))
    top = max(min(s1[1], s1[3]), min(s2[1], s2[3]))
    bottom = min(max(s1[1], s1[3]), max(s2[1], s2[3]))
    if top > bottom or left > right:
        segment_endpoints = []
    elif top == bottom and left == right:
        segment_endpoints.append(left)
        segment_endpoints.append(top)
    else:
        segment_endpoints.append(left)
        segment_endpoints.append(bottom)
        segment_endpoints.append(right)
        segment_endpoints.append(top)
    return segment_endpoints


def intersectLines(pt1, pt2, ptA, ptB):
    DET_TOLERANCE = 0.00000001

    # the first line is pt1 + r*(pt2-pt1)
    # in component form:
    x1, y1 = pt1;
    x2, y2 = pt2
    dx1 = x2 - x1;
    dy1 = y2 - y1

    # the second line is ptA + s*(ptB-ptA)
    x, y = ptA;
    xB, yB = ptB;
    dx = xB - x;
    dy = yB - y;

    DET = (-dx1 * dy + dy1 * dx)

    if math.fabs(DET) < DET_TOLERANCE: return (0, 0, 0, 0, 0)

    # now, the determinant should be OK
    DETinv = 1.0 / DET

    # find the scalar amount along the "self" segment
    r = DETinv * (-dy * (x - x1) + dx * (y - y1))

    # find the scalar amount along the input line
    s = DETinv * (-dy1 * (x - x1) + dx1 * (y - y1))

    # return the average of the two descriptions
    xi = (x1 + r * dx1 + x + s * dx) / 2.0
    yi = (y1 + r * dy1 + y + s * dy) / 2.0
    return (xi, yi, 1, r, s)



line_list = [object for object in acad.iter_objects() if(object.objectName == "AcDbLine")]
print("Line_list:", len(line_list))


c = 0
for x in range(len(line_list)):
    for y in range(len(line_list)):
        if x == y: continue
        c += 1
        s1 = line_list[x].startpoint[:2] + line_list[x].endpoint[:2]
        s2 = line_list[y].startpoint[:2] + line_list[y].endpoint[:2]

        print(c, "x:", x, "y:", y, "s1:", s1, "s2:", s2)
        print(intersectLines(line_list[x].startpoint[:2] , line_list[x].endpoint[:2], line_list[y].startpoint[:2] , line_list[y].endpoint[:2] ))

标签: pythonautocad

解决方案


我认为您只是错过了检查交点 pt 是否在两个部分的边界框内,即 xi 必须在 x1 和 x2 之间。y 也是一样的 - 对于两个段。考虑两条线 x=y 和 y = 1。它们在 1,1 处相交。但是,如果您的段是从 (0,0), (0.5,0.5) 定义的,则它不会相交。


推荐阅读