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

时间:2018-01-13 23:11:39

标签: python python-3.x python-requests shapely shapely.geometry

我按照以下顺序(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

和polygon的坐标(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

我要做的是检查控制点是否在多边形内。如果我的脚本中只有简单的坐标,我通常会这样做,但我不知道如何读取这样的元组。我有一个脚本,现在不起作用。

返回

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)

1 个答案:

答案 0 :(得分:0)

您可以结合使用列表推导和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