SciPy Create 2D Polygon Mask

后端 未结 6 887
慢半拍i
慢半拍i 2020-11-29 19:07

I need to create a numpy 2D array which represents a binary mask of a polygon, using standard Python packages.

  • input: polygon vertices, image dimensions
  • <
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 20:08

    An update on Joe's comment. Matplotlib API has changed since the comment was posted, and now you need to use a method provided by a submodule matplotlib.path.

    Working code is below.

    import numpy as np
    from matplotlib.path import Path
    
    nx, ny = 10, 10
    poly_verts = [(1,1), (5,1), (5,9),(3,2),(1,1)]
    
    # Create vertex coordinates for each grid cell...
    # (<0,0> is at the top left of the grid in this system)
    x, y = np.meshgrid(np.arange(nx), np.arange(ny))
    x, y = x.flatten(), y.flatten()
    
    points = np.vstack((x,y)).T
    
    path = Path(poly_verts)
    grid = path.contains_points(points)
    grid = grid.reshape((ny,nx))
    
    print grid
    

提交回复
热议问题