我曾用在射线法实现过,但是用几个点测试后发现,运算所用时间是PNpoly几百上千倍,不多说,上PNpoly算法实现的代码:
def __is_point_in_polygon(self,pointTp, verts):
"""
- PNPoly算法:判断点是否在不规则区域内(在边界线上也算)
"""
#is_contains_edge=True
x,y=pointTp[0],pointTp[1]
try:
x, y = float(x), float(y)
except:
return False
vertx = [xyvert[0] for xyvert in verts]
verty = [xyvert[1] for xyvert in verts]
# N个点中,横坐标和纵坐标的最大值和最小值,判断目标坐标点是否在这个外包四边形之内
if not verts or not min(vertx) <= x <= max(vertx) or not min(verty) <= y <= max(verty):
return False
# 上一步通过后,核心算法部分
nvert = len(verts)
is_in = False
for i in range(nvert):
j = nvert - 1 if i == 0 else i - 1
if self.__is_in_line((x,y), verts[j], verts[i]):
return True
if ((verty[i] > y) != (verty[j] > y)) and (
x < (vertx[j] - vertx[i]) * (y - verty[i]) / (verty[j] - verty[i]) + vertx[i]):
is_in = not is_in
return is_in