判断点是否位于多边形内部

判断点是否位于多边形内部(reference)

def is_point_in(x, y, points):
    count = 0
    x1 = points[0][0]
    y1 = points[1][0]
    x1_part = (y1 > y) or ((x1 - x > 0) and (y1 == y))
    x2, y2 = '', ''  # points[1]
    points.append((x1, y1))
    for i in range(1, len(points[0])):
        x2 = points[0][i]
        y2 = points[1][i]
        x2_part = (y2 > y) or ((x2 > x) and (y2 == y))
        if x2_part == x1_part:
            x1, y1 = x2, y2
            continue
        mul = (x1 - x)*(y2 - y) - (x2 - x)*(y1 - y)
        if mul > 0:
            count += 1
        elif mul < 0:
            count -= 1
        x1, y1 = x2, y2
        x1_part = x2_part
    if count == 2 or count == -2:
        return True
    else:
        return False

你可能感兴趣的:(小技巧,基础算法记录)