与shapely一起工作时,我遇到了一个奇怪的问题。有两个点p1和p2,第一个点属于多边形,第二个点不属于多边形。当我试图找到包含这两个点的线串与多边形的边界线的端点之间的交集时,我收到消息说没有找到交集。我想知道,怎么可能?
from shapely.geometry import Polygon as SPolygon, Point, LineString
p1 = Point(5.414213562373095, 2.585786437626905)
p2 = Point(15.17279752753168, -7.172797527531679)
l = LineString([p1, p2])
l1 = LineString([(2, 2), (2, 6)])
l2 = LineString([(2, 6), (6, 6)])
l3 = LineString([(6, 6), (6, 2)])
l4 = LineString([(6, 2), (2, 2)])
sp = SPolygon([(2, 2), (2, 6), (6, 6), (6, 2)])
print "Polygon contains p1:", sp.contains(p1)
print "Polygon contains p2:", sp.contains(p2)
for i, line in enumerate((l1, l2, l3, l4)):
res = l.intersects(line)
print "Line {0} intersects l1: {1}".format(i, res)
这里是输出:
Polygon contains p1: True
Polygon contains p2: False
Line 0 intersects l1: False
Line 1 intersects l1: False
Line 2 intersects l1: False
Line 3 intersects l1: False
最佳答案
我把l.intersects(line)
改成l.intersection(line)
在
LINESTRING (6 6, 6 2) at Point (6, 2)
不知道为什么
.instersects()
的行为不同。然后我把p1和p2四舍五入
p1 = Point(round(5.414213562373095, 2), round(2.585786437626905, 2))
p2 = Point(round(15.17279752753168, 2), round(-7.172797527531679, 2))
我有两个十字路口
LINESTRING (6 6, 6 2) at POINT (6 2)
LINESTRING (6 2, 2 2) at POINT (6 2)
此修复也适用于
.intersects()
(2个True)Shapely在浮点精度上有点敏感,我通常可以通过舍入来解决问题。尽管这对你来说可能是不可接受的。
关于python - 匀称的LineString交集工作不正确吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55805121/