检查一个点是否在多边形内部

42

我有一个描述点的类(具有2个坐标x和y),还有一个描述多边形的类,它具有对应于角落的点列表(self.corners)。我需要检查一个点是否在多边形内。

这里是用来检查点是否在多边形内的函数。我使用的是射线法。

def in_me(self, point):
        result = False
        n = len(self.corners)
        p1x = int(self.corners[0].x)
        p1y = int(self.corners[0].y)
        for i in range(n+1):
            p2x = int(self.corners[i % n].x)
            p2y = int(self.corners[i % n].y)
            if point.y > min(p1y,p2y):
                if point.x <= max(p1x,p2x):
                    if p1y != p2y:
                        xinters = (point.y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                        print xinters
                    if p1x == p2x or point.x <= xinters:
                        result = not result
            p1x,p1y = p2x,p2y
         return result

我进行了以下形状和点的测试:

PG1 = (0,0), (0,2), (2,2), (2,0)
point = (1,1)

1
可能是因为你在整数上使用了“/”,这会返回一个整数(向下取整)。你应该改用浮点数进行所有计算。此外,如果p1y == p2y,则xinters可能未定义,但仍然在随后使用。 - Armin Rigo
最好的做法是完全不分割。不要计算 xinters,而是检查 (point.x - p1x)*(p2y-p1y) <= (point.y-p1y)*(p2x-p1x)。然而,如果顶点坐标本来不是整数,则将其转换为整数可能会引入错误。 - chepner
1
或者使用 Python 3,它在除法运算时不会截断为整数。 - Ulrich Eckhardt
使用 (point.x - p1x)*(p2y-p1y) <= (point.y-p1y)*(p2x-p1x) 会影响实际代码的样子是怎样的呢?由于这是一项作业任务,所以我们必须使用 Python 2.7 :( - Helena
@Ulrich & helena:Python 3的除法可以通过在Python 2中使用“from future import division”来启用。另一种选择是只需将分子或分母(或其中一个术语)转换为“float()”。 - martineau
4个回答

65

我建议使用来自matplotlibPath

import matplotlib.path as mplPath
import numpy as np

poly = [190, 50, 500, 310]
bbPath = mplPath.Path(np.array([[poly[0], poly[1]],
                     [poly[1], poly[2]],
                     [poly[2], poly[3]],
                     [poly[3], poly[0]]]))

bbPath.contains_point((200, 100))

如果您想测试多个点,也有一个contains_points函数可供使用。


3
为了使这个工作,你必须首先 import numpy as np - Martin Burch
5
有人测试过 contains_points 的性能与纯Python实现相比吗? - Christophe Roussy
1
为什么变量名叫 'bbPath'? 如果 'bb' 是缩写,是什么的缩写? - nda
1
“bb” 意味着边界框,即使多边形很可能不是一个框 :) - P.R.
1
@ChristopheRoussy 是的,基准测试在 https://dev59.com/zFoV5IYBdhLWcg3wVNaZ 上。 - josch
显示剩余2条评论

3
我建议在那里进行其他一些更改:
def contains(self, point):
    if not self.corners:
        return False

    def lines():
        p0 = self.corners[-1]
        for p1 in self.corners:
            yield p0, p1
            p0 = p1

    for p1, p2 in lines():
        ... # perform actual checks here

注:

  • 一个有5个角的多边形也只有5条边界线,而不是6条,你的循环差了一次。
  • 使用单独的生成器表达式可以清楚地表明您正在逐个检查每条线。
  • 添加了对空行数的检查。但是如何处理长度为零的线和只有一个角的多边形仍然未知。
  • 我还考虑将lines()函数作为普通成员而不是嵌套工具。
  • 与其许多嵌套的if结构相比,您也可以检查反向,然后continue或使用and

1

我正在尝试解决我的项目中的同样问题,我从我的网络中的某人那里得到了这段代码。

#!/usr/bin/env python
#
# routine for performing the "point in polygon" inclusion test

# Copyright 2001, softSurfer (www.softsurfer.com)
# This code may be freely used and modified for any purpose
# providing that this copyright notice is included with it.
# SoftSurfer makes no warranty for this code, and cannot be held
# liable for any real or imagined damage resulting from its use.
# Users of this code must verify correctness for their application.

# translated to Python by Maciej Kalisiak <mac@dgp.toronto.edu>

#   a Point is represented as a tuple: (x,y)

#===================================================================

# is_left(): tests if a point is Left|On|Right of an infinite line.

#   Input: three points P0, P1, and P2
#   Return: >0 for P2 left of the line through P0 and P1
#           =0 for P2 on the line
#           <0 for P2 right of the line
#   See: the January 2001 Algorithm "Area of 2D and 3D Triangles and Polygons"

def is_left(P0, P1, P2):
    return (P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1])

#===================================================================

# cn_PnPoly(): crossing number test for a point in a polygon
#     Input:  P = a point,
#             V[] = vertex points of a polygon
#     Return: 0 = outside, 1 = inside
# This code is patterned after [Franklin, 2000]

def cn_PnPoly(P, V):
    cn = 0    # the crossing number counter

    # repeat the first vertex at end
    V = tuple(V[:])+(V[0],)

    # loop through all edges of the polygon
    for i in range(len(V)-1):   # edge from V[i] to V[i+1]
        if ((V[i][1] <= P[1] and V[i+1][1] > P[1])   # an upward crossing
            or (V[i][1] > P[1] and V[i+1][1] <= P[1])):  # a downward crossing
            # compute the actual edge-ray intersect x-coordinate
            vt = (P[1] - V[i][1]) / float(V[i+1][1] - V[i][1])
            if P[0] < V[i][0] + vt * (V[i+1][0] - V[i][0]): # P[0] < intersect
                cn += 1  # a valid crossing of y=P[1] right of P[0]

    return cn % 2   # 0 if even (out), and 1 if odd (in)

#===================================================================

# wn_PnPoly(): winding number test for a point in a polygon
#     Input:  P = a point,
#             V[] = vertex points of a polygon
#     Return: wn = the winding number (=0 only if P is outside V[])

def wn_PnPoly(P, V):
    wn = 0   # the winding number counter

    # repeat the first vertex at end
    V = tuple(V[:]) + (V[0],)

    # loop through all edges of the polygon
    for i in range(len(V)-1):     # edge from V[i] to V[i+1]
        if V[i][1] <= P[1]:        # start y <= P[1]
            if V[i+1][1] > P[1]:     # an upward crossing
                if is_left(V[i], V[i+1], P) > 0: # P left of edge
                    wn += 1           # have a valid up intersect
        else:                      # start y > P[1] (no test needed)
            if V[i+1][1] <= P[1]:    # a downward crossing
                if is_left(V[i], V[i+1], P) < 0: # P right of edge
                    wn -= 1           # have a valid down intersect
    return wn

0

步骤:

  • 迭代多边形中的所有线段
  • 检查它们是否与一个沿着递增x方向的射线相交

使用此SO问题中的intersect函数

def ccw(A,B,C):
    return (C.y-A.y) * (B.x-A.x) > (B.y-A.y) * (C.x-A.x)

# Return true if line segments AB and CD intersect
def intersect(A,B,C,D):
    return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)

def point_in_polygon(pt, poly, inf):
    result = False
    for i in range(len(poly.corners)-1):
        if intersect((poly.corners[i].x, poly.corners[i].y), ( poly.corners[i+1].x, poly.corners[i+1].y), (pt.x, pt.y), (inf, pt.y)):
            result = not result
    if intersect((poly.corners[-1].x, poly.corners[-1].y), (poly.corners[0].x, poly.corners[0].y), (pt.x, pt.y), (inf, pt.y)):
        result = not result
    return result

请注意,在您的图形中,inf参数应该是x轴上的最大点。

这是不正确的,在多边形[8, 6],[11, 10],[16, 5],[11, 3]中对于点[2, 5]无法工作。编辑:问题可能是射线直接穿过多边形的一个点,导致两个多边形线段切换“result”,将其恢复到先前的状态。 - h345k34cr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接