I think the only issue here is that you need to pass the coordinates to the Polygon constructor, not the list of coordinates. So in trial one, instead of
#Trial 1
newPolygon = Polygon(polygonExteriors, polygonInteriors)
do:
#Trial 1
newPolygon = Polygon(polygonExteriors, [[pt for pt in inner.coords] for inner in polygonInteriors])
As I don't have all of your code, here is an example to demonstrate the solution, which returns the same polygon as inputPolygon:
from shapely.geometry import Polygon
# Example polygon with two holes
inputPolygon = Polygon(((0,0),(10,0),(10,10),(0,10)), (((1,3),(5,3),(5,1),(1,1)), ((9,9),(9,8),(8,8),(8,9))))
polygonExterior = inputPolygon.exterior
polygonInteriors = []
for i in range(len(inputPolygon.interiors)):
# do the stuff with your polygons
polygonInteriors.append(inputPolygon.interiors[i])
newPolygon = Polygon(polygonExterior, [[pt for pt in inner.coords] for inner in polygonInteriors])
A polygon can have multiple holes in it, so the holes
argument is a list of list of coordinate tuples:
>>> exterior = [(2, 8), (7, 8), (7, 3), (2, 3), (2, 8)]
>>> interior = [(4, 7), (4, 5), (6, 5), (6, 7), (4, 7)]
This fails:
>>> pgn = Polygon(exterior, holes=interior)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/rowlings/.local/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 240, in __init__
ret = geos_polygon_from_py(shell, holes)
File "/home/rowlings/.local/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 506, in geos_polygon_from_py
N = exemplar._ndim
AttributeError: 'tuple' object has no attribute '_ndim'
because interior
isn't a list of interior polygons, its just one. So make it a list with one member:
>>> pgn = Polygon(exterior, holes=[interior])
>>> pgn
<shapely.geometry.polygon.Polygon object at 0x7fb3639bc250>
Docs:
The second is an optional unordered sequence of ring-like sequences specifying the interior boundaries or “holes” of the feature.
The "source code" links are great working examples of the shapely API, eg this:
ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]
int = [(1, 0), (0.5, 0.5), (1, 1), (1.5, 0.5), (1, 0)][::-1]
polygon = Polygon(ext, [int])
in https://shapely.readthedocs.io/en/latest/code/polygon.py
Best Answer
If starting with two
Polygon
objects then you can use theobject.difference()
method: