【问题标题】:how to mask the specific array data based on the shapefile如何根据 shapefile 屏蔽特定的数组数据
【发布时间】:2016-04-07 17:41:16
【问题描述】:

这是我的问题:

  • 二维 numpy 数组数据表示每个网格空间的某些属性
  • shapefile 作为研究区域(如城市)的行政区划。

例如:

http://i4.tietuku.com/84ea2afa5841517a.png

整个区域有40x40的网格网络,我想提取紫色区域内的数据。换句话说,我想屏蔽行政之外的数据。 边界到 np.nan。

我的早期尝试

我标记网格编号并选择特定的数组数据到 np.nan 中。

http://i4.tietuku.com/523df4783bea00e2.png

 value[0,:] = np.nan
 value[1,:] = np.nan
       .
       . 
       .
       .

谁能告诉我一个更简单的方法来实现目标?

添加

找到答案here 可以将栅格数据绘制到shapefile中,但数据本身不会改变。

更新-2016-01-16

在一些答案的启发下,我已经解决了这个问题。
对此目标感兴趣的人,请查看我问过的这两个帖子:
1.Testing point with in/out of a vector shapefile
2.How to use set clipped path for Basemap polygon

关键步骤是测试我已经转换为 shapely.polygon 的 shapefile 内部/外部的点。

【问题讨论】:

    标签: python arrays numpy matplotlib matplotlib-basemap


    【解决方案1】:

    最好使用matplotlib:

    def outline_to_mask(line, x, y):
        """Create mask from outline contour
    
        Parameters
        ----------
        line: array-like (N, 2)
        x, y: 1-D grid coordinates (input for meshgrid)
    
        Returns
        -------
        mask : 2-D boolean array (True inside)
        """
        import matplotlib.path as mplp
        mpath = mplp.Path(line)
        X, Y = np.meshgrid(x, y)
        points = np.array((X.flatten(), Y.flatten())).T
        mask = mpath.contains_points(points).reshape(X.shape)
        return mask
    

    或者,您可以使用上述答案中建议的 shapely contains 方法。您可以通过递归细分空间来加速计算,如本要点所示(但 matplotlib 解决方案在我的测试中快 1.5 倍):

    https://gist.github.com/perrette/a78f99b76aed54b6babf3597e0b331f8

    【讨论】:

      【解决方案2】:

      步骤 1. 栅格化 shapefile

      创建一个函数,可以确定坐标(x, y) 处的点是否在该区域内。有关如何将 shapefile 光栅化为与目标蒙版相同尺寸的数组的更多详细信息,请参阅here

      def point_is_in_mask(mask, point):
          # this is just pseudocode
          return mask.contains(point) 
      

      第 2 步。创建你的面具

      mask = np.zeros((height, width))
      value = np.zeros((height, width))
      for y in range(height):
          for x in range(width):
              if not point_is_in_mask(mask, (x, y)):
                  value[y][x] = np.nan
      

      【讨论】:

        猜你喜欢
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-02
        • 2022-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多