【问题标题】:Polygon to binary mask多边形到二进制掩码
【发布时间】:2021-05-20 09:20:05
【问题描述】:

我使用 shapely.geometry 制作了一个多边形,然后将其放入 geopandas 数据框中。 我制作了一个与多边形区域大小相同的数组

我怎样才能把这个多边形变成一个二进制掩码,这样我就可以把我的数组塑造成一个多边形?

感谢您的宝贵时间。

【问题讨论】:

  • 我想我在一些问题中看到了:用matplotlib 绘制多边形并将结果作为数组的图像获取。
  • 这是:stackoverflow.com/questions/64153744/… 你想做什么?
  • @swatchai 完全正确。但我设法使用polygon.contains() 做到了。我将在下周发布我的方法
  • 你好,方法贴出来了吗?我找不到它,并且一直在寻找同样的方法。

标签: python pandas geopandas shapely


【解决方案1】:

我想通了。不是最有效的方法,但确实有效。

首先我在网格上制作一个蒙版,对不在多边形中的数据使用 False(使用 contains 方法)。 其次,我将数组乘以该掩码,然后将 0 作为 NaN。

这是我的代码示例:

# g is anarray with flatten x y coordinates
g = np.stack([
        xi.flatten(),
        yi.flatten(),]) 

# Function to check if in polygon, return bool
def func1d(row, args):
    return args.contains(Point(row[1], row[0]))

# Take mask array and apply along axis, poly is the polygon that we want to use
mask = np.apply_along_axis(func1d, 1, g, args=poly)
g[:,2] = g[:,2]*mask
g[g==0]=[np.NaN] # get 0 be nans (should be a better way to do this but was ok here)
output = g[~np.isnan(g).any(axis=1)] # filter to only save the polygon data

【讨论】:

    猜你喜欢
    • 2021-08-14
    • 2020-03-12
    • 2021-05-29
    • 2022-01-20
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2020-04-13
    • 2022-01-20
    相关资源
    最近更新 更多