How to mask data of a specific array based on shapefile

Here is my question:

  • 2 num num array data represents some property of each grid space
  • shapefile as the administrative division of the field of study (for example, city).

For example:

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

The whole area has a 40x40 mesh grid, and I want to extract the data inside the purple area. In other words, I want to mask data outside the administrative border in np.nan.

My early attempt

I put the grid number and select the specific array data in np.nan.

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

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

Can someone show me an easier way to achieve my goal?

Add

An answer is found here that can display raster data in a shapefile, but the data itself does not change.

-2016-01-16

, .
-, , , :
1. /
2. Baseemap

/ , shapely.polygon.

+4
2

1.

, , (x, y). . , ,

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
+3

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, , . , ( matplotlib 1,5 ):

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

+1

Source: https://habr.com/ru/post/1622687/


All Articles