how to mask the specific array data based on the shapefile

前端 未结 2 843
北荒
北荒 2021-01-01 04:12

Here is my question:

  • the 2-d numpy array data represent some property of each grid space
  • the shapefile as the administrative division of the study a
2条回答
  •  迷失自我
    2021-01-01 04:45

    Best is to use 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
    

    alternatively, you may use shapely contains method as suggested in the above answer. You may speed-up calculations by recursively sub-dividing the space, as indicated in this gist (but matplotlib solution was 1.5 times faster in my tests):

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

提交回复
热议问题