Access individual points in Shapely MultiPoint
Asked Answered
R

2

5

I am working with the Shapely library in Python. I find the intersection of two lines, the return value is given as a MultiPoint object.

How do I deconstruct the object to get the individual points in the intersection?

Here is the code:

from shapely.geometry import LineString, MultiLineString
a = LineString([(0, 1), (0, 2), (1, 1), (2, 0)])
b = LineString([(0, 0), (1, 1), (2, 1), (2, 0)])
x = a.intersection(b)

Output:

print(x) 
MULTIPOINT (1 1, 2 0)

So, in this case, I'd be looking for a way to extract the intersection points (1,1) and (2,0).

Rabblerouser answered 27/6, 2018 at 10:46 Comment(0)
R
5

For Shapely 1.x, you could index the resulting MultiPoint:

>>> str(x)
'MULTIPOINT (1 1, 2 0)'
>>> print(len(x))
2
>>> print(x[0].x)
1.0
>>> print(x[0].y)
1.0

If you want a new list with the coordinates, you can use:

>>> [(p.x, p.y) for p in x]
[(1.0, 1.0), (2.0, 0.0)]
Resinous answered 27/6, 2018 at 10:50 Comment(3)
What about if there are 3 intersection points, you obtain a MultiPoint and a LineString?Rabblerouser
I have installed shapely==2.0.0 and MultiPoint is not iterable or subscriptable now. :/Behka
Try x.geoms[0] (see here )Nelsonnema
G
6

Use .geoms:

from shapely.geometry import LineString
a = LineString([(0, 1), (0, 2), (1, 1), (2, 0)])
b = LineString([(0, 0), (1, 1), (2, 1), (2, 0)])

multipoint = a.intersection(b)
print(multipoint)
#MULTIPOINT (2 0, 1 1)
points = [p for p in multipoint.geoms]
print(points)
#[<POINT (2 0)>, <POINT (1 1)>]
Garret answered 23/6, 2023 at 13:34 Comment(0)
R
5

For Shapely 1.x, you could index the resulting MultiPoint:

>>> str(x)
'MULTIPOINT (1 1, 2 0)'
>>> print(len(x))
2
>>> print(x[0].x)
1.0
>>> print(x[0].y)
1.0

If you want a new list with the coordinates, you can use:

>>> [(p.x, p.y) for p in x]
[(1.0, 1.0), (2.0, 0.0)]
Resinous answered 27/6, 2018 at 10:50 Comment(3)
What about if there are 3 intersection points, you obtain a MultiPoint and a LineString?Rabblerouser
I have installed shapely==2.0.0 and MultiPoint is not iterable or subscriptable now. :/Behka
Try x.geoms[0] (see here )Nelsonnema

© 2022 - 2024 — McMap. All rights reserved.