How to extract Polygons from Multipolygons in Shapely?

醉酒当歌 提交于 2020-01-01 08:55:06

问题


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?


回答1:


Simply do

Polygons = list(Multi)

This extracts the polygons and puts them in a list.




回答2:


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)))


来源:https://stackoverflow.com/questions/38930192/how-to-extract-polygons-from-multipolygons-in-shapely

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!