采用射线法就可以判断一个点是否在多边形内, 只需从点出发向右侧水平做出一条射线,如果跟多边形交点个数为奇数,则点在多边形内,否则在多边形外。看一张图就可以看懂啦

图片来自:https://www.jianshu.com/p/ba03c600a557

输入:P点坐标[px, py]

多边形poly顶点坐标[[x1, y1], [x2, y2], ..., [xn, yn]]

返回:True or False

首先,利用循环对多边形每条边做同样对待。然后,判断是否有跟点P水平右向的射线是否有交点,若有交点,flag就翻转一次。

看程序:

def is_in_poly(p, poly):
    """

    :param p: [x, y]
    :param poly: [[], [], [], [], ...]
    :return:
    """
    px, py = p
    is_in = False
    for i, corner in enumerate(poly):
        next_i = i + 1 if i + 1 < len(poly) else 0
        x1, y1 = corner
        x2, y2 = poly[next_i]
        if (x1 == px and y1 == py) or (x2 == px and y2 == py):  # if point is on vertex
            is_in = True
            break
        if min(y1, y2) < py <= max(y1, y2):  # find horizontal edges of polygon
            x = x1 + (py - y1) * (x2 - x1) / (y2 - y1)
            if x == px:  # if point is on edge
                is_in = True
                break
            elif x > px:  # if point is on left-side of line
                is_in = not is_in
    return is_in


if __name__ == '__main__':
    point = [3, 3]
    poly = [[0, 0], [7, 3], [8, 8], [5, 5]]
    print(is_in_poly(point, poly))

 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐