python - 指向随机形状的多边形?

标签 python algorithm

可以使用著名的光线转换算法轻松确定一个点是否在多边形中。

def point_inside_polygon(x, y, poly):
    """ Deciding if a point is inside (True, False otherwise) a polygon,
    where poly is a list of pairs (x,y) containing the polygon's vertices.
    The algorithm is called the 'Ray Casting Method' """
    n = len(poly)
    inside = False
    p1x, p1y = poly[0]
    for i in range(n):
        p2x, p2y = poly[i % n]
        if y > min(p1y, p2y):
            if y <= max(p1y, p2y):
                if x <= max(p1x, p2x):
                    if p1y != p2y:
                        xinters = (y-p1y) * (p2x-p1x) / (p2y-p1y) + p1x
                    if p1x == p2x or x <= xinters:
                        inside = not inside
        p1x, p1y = p2x, p2y
    return inside

但是如果多边形不是完全凸的呢?

如何确定一个点是否在给定边界点的随机形状多边形中?

假设我有一个像这样的边界点多边形

enter image description here

我该怎么做?

最好使用 Python,但也欢迎任何通用解决方案。

最佳答案

转换一条光线,并计算光线穿过多边形的次数。 (如果边正好位于射线上,这可能会变得烦人且容易出错。)如果它是奇数,则该点位于多边形中。否则,它不是。

关于python - 指向随机形状的多边形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20138932/

相关文章:

python - 如何对嵌套字典的值求和

Python 将 xml 解析为数据帧,无需明确命名标签

algorithm - 未保存更改检测的实现

algorithm - 寻找一组点的旋转中心

c - 是否有一个好的算法来对未排序的、平衡的、二叉树进行排序(这比仅仅构建一棵新树更好)?

algorithm - 在各种组合中增加值(value)

algorithm - 在近似树皮刻度上获取等距间隔

python - Django:选择 JsonField 作为 new_name?

python - 从嵌套 xml 创建数据框并生成 csv

python - 从 GStreamer 实时接收 Numpy 数组