Search code examples
pythonpandasgeopandasshapely

Polygon to binary mask


I've made a polygon using shapely.geometry, then put it into a geopandas dataframe. I've made an array with the same size as the polygon zone

How can I turn this polygon into a binary mask, so I can shape my array as a polygon too?

Thanks for your time.


Solution

  • I figured it out. Not the most efficient method but it worked.

    First I make a mask on the grid, with False on data that is not in the polygon (using contains method). Second I multiply the array by that mask, then take 0 as NaNs.

    Here is an example of my code :

    # 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