Arrays 以矢量化方式批处理具有唯一位置的窗口掩码-Python/NumPy

Arrays 以矢量化方式批处理具有唯一位置的窗口掩码-Python/NumPy,arrays,image,performance,numpy,vectorization,Arrays,Image,Performance,Numpy,Vectorization,我需要为一组图像创建随机布尔掩码。每个遮罩是一个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_coo

我需要为一组图像创建随机布尔掩码。每个遮罩是一个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循环

另外:批处理中每个图像的遮罩必须不同(不能对每个图像使用相同的遮罩)

我们可以利用based获得滑动窗口,从而解决我们的问题

基于
视图
,它将尽可能高效

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]]])