简体   繁体   English

如何从 Shapely 中的多多边形中提取多边形?

[英]How to extract Polygons from Multipolygons in Shapely?

I'm trying to extract the polygons from multipolygons in Shapely.我正在尝试从 Shapely 中的多面体中提取多边形。 I can transform a list of polygons into multipolygons using MultiPolygon from Shapely.我可以使用 Shapely 中的MultiPolygon将多边形列表转换为多面体。

>>> 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 ie given a multipolygon how can I convert it to separate polygons?有谁知道我怎样才能扭转这个过程,即给定一个多面体,我怎样才能将它转换为单独的多边形?

Simply do 简单地做

Polygons = list(Multi)

This extracts the polygons and puts them in a list. 这将提取多边形并将它们放入列表中。

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() ": 根据集合的文档 ,其中包括MultiPointMultiLineStringMultiPolygon等类,它们的成员可以“ 通过geoms属性或通过使用inlist()的迭代器协议访问

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

为了避免在使用这个非常好的答案时出现弃用警告,请执行以下操作:

Polygons = list(Multipolygon.geoms)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM