shapely.intersection 方法返回错误的答案

huangapple go评论91阅读模式
英文:

Method shapely.intersection returns a wrong answer

问题

我尝试使用方法shapely.intersection在二维中找到两条边的交点,但得到了错误的答案。
Shapely模块版本为2.0.1

from shapely.geometry import LineString
a = LineString([[30.0,0.0],[36.0,30.0]])
b = LineString([[32.8,14.0],[35.2,26.0]])
intersection = a.intersection(b)

很容易检查到边b完全位于边a上,因此交点的结果应该等于b,但是代码返回了一个点(边b的中心点)
Point(34,20)

英文:

I try to find intersection of two edges in 2D using method shapely.intersection and get a wrong answer
Shapely module v.2.0.1

from shapely.geometry import LineString
a = LineString([[30.0,0.0],[36.0,30.0]])
b = LineString([[32.8,14.0],[35.2,26.0]])
intersection = a.intersection(b)

It is easy to check that edge b entirely lays on edge a, and so the result of intersection will be equals b
but code returns one point (the center of the edge b)
Point(34,20)

答案1

得分: 1

你所看到的是浮点数运算中不完美精度的结果。这个问题详细讨论了这个主题。

shapely.intersection 提供了指定网格大小以限制计算精度的选项:

> shapely.intersection(a, b, 0.1)
<MULTILINESTRING ((32.8 14, 34 20), (34 20, 35.2 26))>

返回的 MultiLineString 由多个线段组成(我没有深入研究原因)。您可以使用返回的 MultiLineStringoriented_envelope 属性,将连接的线段缩减回单个 LineString(只要它们实际上是连接的且共线的):

> line_string = shapely.intersection(a, b, 0.1)
> line_string.oriented_envelope
<LINESTRING (32.8 14, 35.2 26)>
英文:

What you're seeing is the result of imperfect precision in floating point math. This question discusses the topic extensively.

shapely.intersection gives you the option to specify a grid size to limit the precision of the calculations:

> shapely.intersection(a, b, 0.1)
<MULTILINESTRING ((32.8 14, 34 20), (34 20, 35.2 26))>

The returned MultiLineString consists of multiple segements (I haven't looked into why). You can use the oriented_envelope property of the returned MultiLineString to reduce the connected segments back into a single LineString (as long as they are actually connected and colinear):

> line_string = shapely.intersection(a, b, 0.1)
> line_string.oriented_envelope
<LINESTRING (32.8 14, 35.2 26)>

huangapple
  • 本文由 发表于 2023年7月28日 00:59:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76781968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定