Extract Points from Shapely Polygon
We can extract points from a polygon using the mapping() function, or with detail, extracting the polygon's boundaries.
When we want to extract the points that define a shapely polygon, we have various alternatives.
Let’s first create a polygon by computing the difference between two other polygons. The resulting polygon will have a hole in it, making this example less trivial.
from shapely.geometry import Polygon
poly1 = Polygon( [(0, 0), (1,0), (1,1), (0,1) ] )
poly2 = Polygon( [(0.25, 0.25), (0.5,0.25), (0.5,0.5), (0.25,0.5) ] )
polydiff = poly1.difference(poly2)
Extracting exterior and interior boundaries
Each polygon object has an exterior LinearRing, and zero or multiple interior LinearRings. We can extract the coordinates of these rings as follows:
xe,ye = polydiff.exterior.xy
for LinearRing in polydiff.interiors:
xi,yi = LinearRing.xy
This way of accessing the polygon’s points is more direct and easier to unpack x and y coordinates.
Using the mapping() function
An alternative method, is to rely on the mapping()
function in shapely. According to the Shapely’s User Manual, this function returns a new object with the coordinates copied from the original one.
Let’s apply this function to our polygon and see what turnes out.
from shapely.geometry import mapping
obj = mapping(polydiff)
print(obj['coordinates'])
(((0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0), (0.0, 1.0)), ((0.5, 0.25), (0.5, 0.5), (0.25, 0.5), (0.25, 0.25), (0.5, 0.25)))
We see that we got a nested iterable structure. In our case, as we have both exterior and interior boundaries, we could unpack it as follows
exterior, interior = obj['coordinates']
plot(exterior)
((0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0), (0.0, 1.0))
We also see that the boundary’s end-point is repeated, and that the x and y coordinates are not unpacked, but stored in tuples. This is part of the trade-off to consider, depending on the application.