2

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)

Grag2015
  • 591
  • 9
  • 15

1 Answers1

1

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)>
Woodford
  • 3,746
  • 1
  • 15
  • 29
  • thank you, your solution works well, I've tried to change parameter `grid_size` but I setted too low value - about 1e-9 – Grag2015 Jul 27 '23 at 19:48
  • One comment has appeared - after adding `grid_size` = 0.1 `intersection` returns `b` as 2 edges ``. Is it possible to get whole edge `b`? – Grag2015 Jul 28 '23 at 08:47
  • 1
    Edited to add how you can combine segments – Woodford Jul 28 '23 at 17:24
  • But why does method `intersects` not have parameter `grid_size`? In my code I am trying to check does `A` intersect `B` or not and then I will find the intersection. But how to do this if methods`intersects` and `intersection` have the different precision ? – Grag2015 Aug 27 '23 at 19:21