How to make holes in a Polygon in shapely python,

2020-08-22 07:13发布

问题:

In python, I have a plain Polygon "outer" and a list of Polygons "inners". I want to make holes in my polygon using this list.

from shapely.geometry import Polygon

# polygon with 1 hole in the middle
p = Polygon(((0,0),(10,0),(10,10),(0,10)), (((4,4),(4,6),(6,6),(6,4)), ))
print p.wkt
# POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (4 4, 4 6, 6 6, 6 4, 4 4))

# other constructor, does not work (no hole) :
outer = Polygon(((0,0),(10,0),(10,10),(0,10),(0,0)))
inners = (Polygon(((4,4),(4,6),(6,6),(6,4),(4,4))), )
p = Polygon(outer, inners)
print p.wkt
# POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))

How to build p given outer and inners ?

回答1:

Sorry, I've just found a solution, given outer as a plain Polygon and inners as a list of plain Polygons (each of them contained in outer) :

p = Polygon(outer.exterior.coords, [inner.exterior.coords for inner in inners])

The Polygon constructor only works with coordinates as input, not with other Polygons such as :

p = Polygon(outer, inners)