首页 > 解决方案 > 在滑动窗口中应用 np.where

问题描述

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

import numpy as np

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

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

我想在滑动窗口中应用这个掩码,类似于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?我希望会有某种滑动窗口技术或卷积/相关。

标签: pythonnumpysliding-window

解决方案


使用带有 reshape 的广播,这样您就不需要额外的内存来重复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)

推荐阅读