Stefan Karlsson
Stefan Karlsson

Reputation: 1085

how to change orientation of multipolygon in shapely

In Shapely lib, there exists a handy function to set the orientation of polygon. Assuming sz is regular shapely Polygon:

sz = shapely.geometry.polygon.orient(sz, sign=1.0)

If instead sz is a Multipolygon, then above fails. Since it is iterable, I also tried the following:

# Fails:    
for ii in range(len(sz)):
    sz[ii] = shapely.geometry.polygon.orient(sz[ii], sign=1.0)

But multipolygons do not support item assignment. A solution is to grab all of the polygons, change the orientation, and then create a new Multipolygon:

# Works, but I hope for something better:
szl = []
for s in sz:
   szl.append(shapely.geometry.polygon.orient(s, sign=1.0))
sz = shapely.geometry.MultiPolygon(szl)

This is alot of overhead in execution and memory, and is not as easy to understand as the solution for single polygon. Is there a nicer solution?

Upvotes: 0

Views: 1169

Answers (1)

Felipe D.
Felipe D.

Reputation: 1271

You could use list comprehension. Also, to make it a bit less cumbersome to read, you could import the function you want directly:

from shapely.geometry.polygon import orient
from shapely.geometry import MultiPolygon

sz = MultiPolygon([orient(s, sign=1.0) for s in sz])

This is an admittedly ugly solution, but it's likely going to be a bit faster and more readable.

Upvotes: 2

Related Questions