pythonshapely

Access individual points in Shapely MultiPoint


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).


Solution

  • 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)]