我有一个充满 0 和 1 的 numpy 数组。 我正在尝试将填充有 1 的单元格转换为多边形。为此,我使用 rasterio、shapely 和 geopandas。
def flooded_to_shapefile(array, transform, filename):
shapes = rasterio.features.shapes(array, transform = transform)
# Select only cells with 1's
polygons = [shapely.geometry.Polygon(shape[0]["coordinates"][0])
for shape in shapes if shape[1] == 1]
# Create dataframe with polygons
df = gpd.GeoDataFrame(polygons)
df.columns = ["geometry"]
df.set_geometry(col='geometry', inplace=True)
df.to_file(filename)
我遇到的问题是,在矩阵中,我有一些洞没有在最终的多边形中正确表示。例如,看看这个:
当我运行代码时,我得到以下信息。
如您所见,例如,星形已合并到多边形中,但由于它包含 0 个值,因此不应合并到多边形中。线条 shape[1] == 1 应该防止星星被选中(如here所示,但多边形仍然“闭合”。您知道为什么会发生这种情况吗?
初始化Polygon对象使用2个参数,shell(外环)和holes(内环)。你只给它外壳,这样你就得到一个填充的多边形。
我认为你可以将栅格中的每个
shape
(类似geojson的字典)作为shapely.geometry.shape函数的参数,以获得带孔的多边形。shapes
应该可以解决问题