所以我编写了一些代码来检查点[(x,y)]是否位于多边形[(x,y),(x,y),(x,y),(x,y)]内但是如果点位于边界或顶点上,代码将失败,我需要将其归类为位于多边形内。这是代码:
def areasign(poly):
sumarea = 0
for i in range(0, len(poly)-1):
xi = poly[i][0]
yi = poly[i][1]
xj = poly[i+1][0]
yj = poly[i+1][1]
sumarea = sumarea + ((xi*yj)-(yi*xj))
if sumarea == 0: return 0
if sumarea < 0: return -1
if sumarea > 0: return 1
def lineintersection(xy, ij):
xyi = []
xyj = []
ijx = []
ijy = []
xyi.extend(xy)
xyj.extend(xy)
xyi.append(ij[0])
xyj.append(ij[1])
xyi.append(xy[0])
xyj.append(xy[0])
ijx.extend(ij)
ijy.extend(ij)
ijx.append(xy[0])
ijy.append(xy[1])
ijx.append(ij[0])
ijy.append(ij[0])
a = areasign(xyi)
b = areasign(xyj)
c = areasign(ijx)
d = areasign(ijy)
if (a!= b) and (c!=d):
return True
else:
return False
def openpointfile(fname):
p = []
f = open(fname)
for line in f:
line = line.replace('POINT(', '')
line = line.replace(')', '')
vals = line.split(' ')
res = map(float, vals)
ctuple = tuple(res)
p.append(ctuple)
print ctuple
f.close()
return p
points = openpointfile('C:/Users/Dan/Documents/Informatics/Data/Point_On_Line.txt')
def openpolygonfile(fname):
p = []
f = open(fname)
for line in f:
line = line.replace('POLYGON((', '')
line = line.replace('))', '')
s = line.split(',')
poly = []
for coord in s:
vals = coord.split(' ')
res = map(float, vals)
ctuple = tuple(res)
poly.append(ctuple)
p.append(poly)
f.close()
return p
polys = openpolygonfile('C:/Users/Dan/Documents/Informatics/Data/Polygon_On_Line.txt')
def pointinpoly(points, polys):
infinity = tuple([100000000.0, 100000010.0])
sum = 0
testline = (points, infinity)
for i in range(0, len(poly)-1):
start = poly[i]
end = poly[i+1]
line = (start, end)
l = lineintersection(line, testline)
if l == True:
sum = sum + 1
if sum % 2 == 0:
return False
else:
return True
pointcount = 0
for point in points:
pointcount = pointcount + 1
polycount = 0
for poly in polys:
polycount = polycount + 1
l = pointinpoly(point, poly)
res = 'Point ' + str(pointcount) + ' lies within Polygon ' + str(polycount) + ' = ' + str(l)
print l
print (res)
就像我之前所说的,如果点位于边界或顶点上,这不起作用,我有这个功能,我在这里找到似乎工作,但我找不到一种方法将我的文件变为正确函数的格式,并让它迭代一个多边形列表。
def point_in_poly(x,y,poly):
# check if point is a vertex
if (x,y) in poly: return "IN"
# check if point is on a boundary
for i in range(len(poly)):
p1 = None
p2 = None
if i==0:
p1 = poly[0]
p2 = poly[1]
else:
p1 = poly[i-1]
p2 = poly[i]
if p1[1] == p2[1] and p1[1] == y and x > min(p1[0], p2[0]) and x < max(p1[0], p2[0]):
return "IN"
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
if inside: return "IN"
else: return "OUT"
有关如何将该函数构建到现有代码中的任何帮助或有关新函数的任何帮助,可用于检查点是位于多边形的边界还是位于顶点上