简体   繁体   English

在滑动窗口中应用 np.where

[英]Applying np.where in a sliding window

I have an array of True / False values which I want to use as a repeating mask over another array of a different shape.我有一个True / False值数组,我想将其用作另一个不同形状数组的重复掩码。

import numpy as np

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

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

I want to apply this mask in a sliding window, similar to the where function on the array.我想在滑动窗口中应用这个掩码,类似于数组上的where函数。 Currently, I use np.kron to simply repeat the mask to match the dimensions of the array:目前,我使用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

Is there any elegant way to do this same operation, without repeating the mask into the same shape as array ?是否有任何优雅的方法可以执行相同的操作,而无需将mask重复为与array相同的形状? I was hoping there would be some kind of sliding window technique or convolution/correlation.我希望会有某种滑动窗口技术或卷积/相关性。

Use broadcasting with reshape so you wouldn't need extra memory for the repeated mask :将广播与重塑一起使用,这样您就不需要为重复的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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM