Created
April 2, 2020 17:09
-
-
Save zhaomengit/c32a5dcc9dfaab83baacffa8d1e53faa to your computer and use it in GitHub Desktop.
PNPoly算法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def point_in_polygon(x, y, verts): | |
""" | |
- PNPoly算法 | |
- xyverts [(x1, y1), (x2, y2), (x3, y3), ...] | |
""" | |
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 ((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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment