Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract Polygons from Multipolygons in Shapely?

Tags:

python

shapely

I'm trying to extract the polygons from multipolygons in Shapely. I can transform a list of polygons into multipolygons using MultiPolygon from Shapely.

>>> Multi = MultiPolygon([shape(pol['geometry']) for pol in fiona.open('data.shp')]) 

And,

>>> Multi.wkt
'MULTIPOLYGON (((249744.2315302934148349 142798.1643468967231456, 250113.7910872535139788 142132.9571443685272243, 250062.6213024436729029 141973.7622582934272941, 249607.7787708004761953 141757.7120557629095856, 249367.7742475979903247 142304.6840291862317827, 249367.7742475979903247 142304.6840291862317827, 249744.2315302934148349 142798.1643468967231456)), 
               ((249175.7899173096520826 142292.5352640640921891, 249367.7742475979903247 142304.6840291862317827, 249607.7787708004761953 141757.7120557629095856, 249014.4539607730694115 141876.1348429077770561, 249175.7899173096520826 142292.5352640640921891)))'

Does anybody know how can I reverse the process i.e. given a multipolygon how can I convert it to separate polygons?

like image 510
Rahul Avatar asked Aug 13 '16 07:08

Rahul


1 Answers

According to documentation on collections, which include such classes as MultiPoint, MultiLineString and MultiPolygon, their members can be "accessed via the geoms property or via the iterator protocol using in or list()":

from shapely.geometry import MultiPolygon, Polygon

multipolygon = MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)]),
                             Polygon([(0, 0), (1, 1), (0, 1)])])

polygons = list(multipolygon)
print(*polygons)
# POLYGON ((0 0, 1 1, 1 0, 0 0)) POLYGON ((0 0, 1 1, 0 1, 0 0))

polygons = list(multipolygon.geoms)
print(*polygons)
# POLYGON ((0 0, 1 1, 1 0, 0 0)) POLYGON ((0 0, 1 1, 0 1, 0 0))

for polygon in multipolygon:  # same for multipolygon.geoms
    print(polygon)
# POLYGON ((0 0, 1 1, 1 0, 0 0))
# POLYGON ((0 0, 1 1, 0 1, 0 0))

You can also extract individual geometries by their index:

print(multipolygon[0])
POLYGON ((0 0, 1 1, 1 0, 0 0))

Slicing them will give you a collection though:

print(multipolygon[:1])
MULTIPOLYGON (((0 0, 1 1, 1 0, 0 0)))
like image 198
Georgy Avatar answered Sep 18 '22 18:09

Georgy