python - 在滑动窗口中应用 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
?我希望会有某种滑动窗口技术或卷积/相关。
解决方案
使用带有 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)
推荐阅读
- javascript - Vue.js“导入”在外部 js 文件中不起作用
- javascript - 事件是如何传递给这个函数的?
- c - 从 Go 传递 C-struct 时出现 _Ctype_struct_0 错误
- java - FCM 通知未发送声音
- spring - hibernate 是否有一些内部“提交 id”?
- python - Python Dash/Plotly 不能正确显示图表?
- python - 连接两个数据框的问题。两者都具有相同的行数,但它们不能完美地合并
- kubernetes-helm - 嵌套在 helm 图表表达式中
- r - 在数字字段的每个级别上回归的线性模型
- linux - 为什么 jq 有时需要过滤器表达式,有时不需要?