以矢量化方式具有独特位置的窗口掩码批次 - Python / NumPy

Batch of windowed masks with unique positions in vectorized way - Python / NumPy

我需要为一组图像创建随机布尔掩码。每个掩码都是一个由 1 组成的数组,其中包含 6 个随机方块,其中的值为 0。方块的长度为 56 个像素。可以使用以下代码创建掩码:

mask = np.ones(shape=(3, h, w))
for _ in range(6):
        x_coordinate = np.random.randint(0, w)
        y_coordinate = np.random.randint(0, h)
        mask[:, x_coordinate: x_coordinate + 56, y_coordinate: y_coordinate + 56] = 0

现在我想做的一件棘手的事情是将这个过程矢量化为一批图像。这可能吗?现在,我只是为我的批处理中的每个图像使用一个简单的 for 循环来调用此函数,但我想知道是否有办法完全避免 for 循环。

另外:批处理中每张图像的蒙版必须不同(不能对每张图像使用相同的蒙版)

我们可以利用 np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows and hence solve our case here. .

基于views,它将尽可能高效!

from skimage.util.shape import view_as_windows

N = 3 # number of images in the batch
image_H,image_W = 5,7 # edit to image height, width
bbox_H,bbox_W = 2,3  # edit to window height, width to be set as 0s

w_off = image_W-bbox_W+1
h_off = image_H-bbox_H+1
M = w_off*h_off

R,C = np.unravel_index(np.random.choice(M, size=N, replace=False), (h_off, w_off))

mask_out = np.ones(shape=(N, image_H, image_W), dtype=bool)
win = view_as_windows(mask_out, (1, bbox_H,bbox_W))[...,0,:,:]
win[np.arange(len(R)),R,C] = 0

如果您不介意重复掩码,只需在代码中使用 replace=True

给定输入参数的示例输出 -

In [6]: mask_out
Out[6]: 
array([[[ True,  True,  True,  True,  True,  True,  True],
        [ True,  True, False, False, False,  True,  True],
        [ True,  True, False, False, False,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True]],

       [[ True,  True,  True,  True,  True,  True,  True],
        [ True, False, False, False,  True,  True,  True],
        [ True, False, False, False,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True]],

       [[ True,  True,  True,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True],
        [False, False, False,  True,  True,  True,  True],
        [False, False, False,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True]]])