从文本文件中获取坐标行并检查点是否在多边形内

Getting rows of coordinates from text file and checking whether points are inside polygon

我在文本文件中有数百个坐标(控制点),顺序如下 (x y):

5480.000 -4880.000
5480.000 -4860.000
5480.000 -4840.000
5480.000 -4820.000
5480.000 -4800.000
5480.000 -4780.000
5480.000 -4760.000
5480.000 -4740.000
5480.000 -4720.000
5480.000 -4700.000

多边形坐标(12):

259.59 229.87
329.07 284.19
397.76 262.62
480.03 397.60
336.26 545.37
325.88 400.00
142.17 440.74
92.65 275.40
158.95 265.02
180.51 196.33
265.97 119.65
259.59 229.87

我要做的是检查控制点是否在多边形内。一般来说,如果我的脚本中有几个简单的坐标,我就可以做到,但我不知道如何读取这样的元组。我有一个脚本目前无法使用。

它returns

File "C:/......../test.py", line 16, in <module> xc.append(row[0]) IndexError: list index out of range

最好的解决方案是多边形内的坐标出现在终端中。

from shapely.geometry import Point, Polygon
import csv

poly = open(r"polygon.txt","r")
control = open(r"controlPoints.txt","r")

xp, yp = [], []
for l in poly:
    row = l.split()
    xp.append(row[0])
    yp.append(row[1])

xc,yc = [], []
for l in control:
    row = l.split()
    xc.append(row[0])
    yc.append(row[1])
print(xc)
print(yc)

# Create Point objects

p = Point(xc, yc)

# Create a Polygon 

coords = [xp, yp]
poly1 = Polygon(coords)
print(poly1)

# CHECK 

p.within(poly1)
print(p)

check=poly1.contains(p)
print(check)

您可以结合使用列表理解和 map() 来创建所需的嵌套列表:

poly = Polygon([tuple(map(float, row.split())) for row in open(r"polygon.txt","r") if len(row.split()) == 2])
rawPoints = [tuple(map(float, row.split())) for row in open(r"controlPoints.txt","r") if len(row.split()) == 2]

for pt in rawPoints:
    p = Point(*pt)
    print (p, p.within(poly), poly.contains(p))

这会打印:

POINT (5480 -4880) False False
POINT (5480 -4860) False False
POINT (5480 -4840) False False
POINT (5480 -4820) False False
POINT (5480 -4800) False False
POINT (5480 -4780) False False
POINT (5480 -4760) False False
POINT (5480 -4740) False False
POINT (5480 -4720) False False
POINT (5480 -4700) False False