How do you get/extract the points that define a shapely
polygon?
Thanks!
Example of a shapely polygon
from shapely.geometry import Polygon
# Create polygon from lists of points
x = [list of x vals]
y = [list of y vals]
polygon = Polygon(x,y)
How do you get/extract the points that define a shapely
polygon?
Thanks!
Example of a shapely polygon
from shapely.geometry import Polygon
# Create polygon from lists of points
x = [list of x vals]
y = [list of y vals]
polygon = Polygon(x,y)
You can convert a shapely Polygon to a NumPy array using NumPy.array. I find using NumPy arrays more useful than the arrays returned by coords.xy, since the coordinates are paired, rather than in two one-dimensional arrays. Use whichever is more useful to your application.
It took me a while to learn that a Polygon has an exterior boundary and possibly several interior boundaries. I am posting here because some of the answers don't reflect that distinction, though to be fair the original post did not use as an example a polygon with interior boundaries.
The points forming the exterior boundary are arranged in a CoordinateSequence, which can be obtained as
You can find the length of this object using
len(polygon.exterior.coords)
and can index the object like a list. To get the first vertex, for example, usepolygon.exterior.coords[0]
. Note that the first and last points are the same; if you want a list consisting of the vertices without that repeated point, usepolygon.exterior.coords[:-1]
.You can convert the CoordinateSequence (including the repeated vertex) to a list of points thus:
Similarly, the CoordinateSequence consisting of the vertices forming the first interior boundary is obtained as
polygon.interiors[0].coords
, and the list of those vertices (without the repeated point) is obtained aspolygon.interiors[0].coords[:-1]
.I used this:
Polygon created with:
p = Polygon([(0,0),(1,1),(1,0),(0,0)])
returns:If you really want the shapely point objects that make up the polygon, and not just tuples of coordinates, you can do that this way:
So, I discovered the trick is to use a combination of the
Polygon
class methods to achieve this.If you want geodesic coordinates, you then need to transform these back to WGS84 (via
pyproj
,matplotlib
'sbasemap
, or something).You can use any of the two following methods.
1)
The above code prints the following. Note that (1,0) is printed twice, since exterior.coords returns an ordered sequence that completes the polygon.
2)
It outputs the following