简体   繁体   中英

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.

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. Currently, I use np.kron to simply repeat the mask to match the dimensions of the array:

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 ? 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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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