这是一个实现@IsaacSutherland 方法(已接受的答案)的函数,并进行了一些我认为有用的修改。欢迎评论!
poly_mask() 接受多个多边形作为输入,因此输出掩码可以由多个最终不连接的多边形区域组成。
此外,因为在某些情况下 0 不是一个好的掩码值(例如,如果 0 是要应用掩码的数组的有效值),我添加了一个 value 关键字来设置实际的掩码值(例如,非常小/大数字或 NAN):为了实现这一点,掩码被转换为浮点数组。
def poly_mask(shape, *vertices, value=np.nan):
"""
Create a mask array filled with 1s inside the polygon and 0s outside.
The polygon is a list of vertices defined as a sequence of (column, line) number, where the start values (0, 0) are in the
upper left corner. Multiple polygon lists can be passed in input to have multiple,eventually not connected, ROIs.
column, line # x, y
vertices = [(x0, y0), (x1, y1), ..., (xn, yn), (x0, y0)] or [x0, y0, x1, y1, ..., xn, yn, x0, y0]
Note: the polygon can be open, that is it doesn't have to have x0,y0 as last element.
adapted from: https://stackoverflow.com/questions/3654289/scipy-create-2d-polygon-mask/64876117#64876117
:param shape: (tuple) shape of the output array (height, width)
:param vertices: (list of tuples of int): sequence of vertices defined as
[(x0, y0), (x1, y1), ..., (xn, yn), (x0, y0)] or
[x0, y0, x1, y1, ..., xn, yn, x0, y0]
Multiple lists (for multiple polygons) can be passed in input
:param value: (float or NAN) The masking value to use (e.g. a very small number). Default: np.nan
:return: (ndarray) the mask array
"""
width, height = shape[::-1]
# create a binary image
img = Image.new(mode='L', size=(width, height), color=0) # mode L = 8-bit pixels, black and white
draw = ImageDraw.Draw(img)
# draw polygons
for polygon in vertices:
draw.polygon(polygon, outline=1, fill=1)
# replace 0 with 'value'
mask = np.array(img).astype('float32')
mask[np.where(mask == 0)] = value
return mask
我更喜欢直接使用shape 作为输入而不是(宽度,高度),这样我就可以像这样使用它:
polygon_lists = [
[(x0, y0), (x1, y1), ..., (xn, yn), (x0, y0)],
[# ... another sequence of coordinates...],
[# ...yet another sequence of coordinates...],
]
my_mask = poly_mask(my_array.shape, *polygon_lists)
其中my_array 是必须应用蒙版的数组(当然,也可以是其他具有相同形状的数组)。
my_array_masked = my_array * my_mask