在滑动 window 中应用 np.where

Applying np.where in a sliding window

我有一个 True/False 值数组,我想将其用作另一个不同形状数组的重复掩码。

import numpy as np

mask = np.array([[ True, True],
                 [False, True]])

array = np.random.randint(10, size=(64, 64))

我想在滑动 window 中应用此蒙版,类似于数组上的 where 函数。目前,我使用 np.kron 简单地重复掩码以匹配数组的维度:

layout = np.ones((array.shape[0]//mask.shape[0], array.shape[1]//mask.shape[1]), dtype=bool)
mask = np.kron(layout, mask)
result = np.where(mask, array, 255) # example usage

有没有什么优雅的方法可以完成同样的操作,而不用将 mask 重复成与 array 相同的形状?我希望会有某种滑动 window 技术或 convolution/correlation.

将广播与整形一起使用,这样您就不需要额外的内存来重复 mask:

x, y = array.shape[0]// mask.shape[0], array.shape[1] // mask.shape[1]

result1 = np.where(mask[None, :, None], 
                  array.reshape(x, mask.shape[0], y, mask.shape[1]), 
                  255).reshape(array.shape)

你可以试试 np.tile:

np.where(np.tile(mask, (a//m for a,m in zip(array.shape, mask.shape))), array, 255)