gpt4 book ai didi

python: bool 数组到多边形

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:13 24 4
gpt4 key购买 nike

我有一个 bool 数组,其中包含一个 True 值的连接组件,我想将其边界转换为多边形,例如在匀称。

假设我的数组是img,我可以得到这样的边框索引

import numpy as np
from skimage.morphology binary_erosion

border_indices = np.transpose(np.nonzero(np.logical_xor(binary_erosion(img), img)))

但是仅仅将它们输入 shapely.Polygon 对象是行不通的,因为这些点不是沿着边界排序的,而是在增加 xy 值。

也许可以使用 alpha 形状来解决这个问题(请注意,我不是在寻找凸包),但也许有人可以建议一种更简单的方法来获取边界多边形,最好直接在原始数组上操作.

最佳答案

听起来 rasterio.features.shapes 就是您要找的东西。一个应该说明该过程的简单示例:

import rasterio.features
import shapely.geometry
import numpy as np

im = np.zeros([5, 5], dtype=np.uint8)
im[1:-1, 1:-1] = 1

shapes = rasterio.features.shapes(im)

shapes 是一个带有 (geometry, value) 对的生成器。要获取值等于 1 的位置对应的几何图形:

polygons = [shapely.geometry.Polygon(shape[0]["coordinates"][0]) for shape in shapes if shape[1] == 1]

这将创建一个 shapely 多边形列表,这些多边形对应于数组中值等于 1 的区域。

print(polygons)
[<shapely.geometry.polygon.Polygon object at 0x7f64bf9ac9e8>]

关于python: bool 数组到多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com