python - 如何获取数组滑动窗口 View 中最大元素的矩阵位置?

标签 python numpy sliding-window

我使用 NumPy 中的 amaxsliding_window_view 函数成功找到了每个滑动窗口 View 中数组的最大值,如下所示:

import numpy as np


a = np.random.randint(0, 100, (5, 6))  # 2D array

array([[51, 92, 14, 71, 60, 20],
       [82, 86, 74, 74, 87, 66],
       [23,  2, 21, 52,  1, 87],
       [29, 37,  1, 63, 59, 20],
       [32, 75, 57, 21, 83, 48]])

windows = np.lib.stride_tricks.sliding_window_view(a, (3, 3))
np.amax(windows, axis=(2, 3))

array([[92, 92, 87, 87],
       [86, 86, 87, 87],
       [75, 75, 83, 87]])

现在,我试图在考虑窗口的情况下找到原始数组中最大值的位置。

预期输出

The first element i.e. `92` should give position `(1, 0)`.
The second element i.e. `92` should give position `(1, 0)`.
The third element i.e. `87` should give position `(4, 1)`.
.
.
The seventh element i.e. `87` should give position `(4, 1)`.
The twelveth element i.e. `87` should give position `(5, 2)`.
.
so on

注意:每个值只需要一个位置。因此,如果窗口内有多个位置,则仅返回第一个。

最佳答案

此解决方案给出每个窗口的索引,但如果最大值在某个窗口中出现两次,则不会给出唯一索引:

maxvals = np.amax(windows, axis=(2, 3))
# array([[92, 92, 87, 87],
#        [86, 86, 87, 87],
#        [75, 75, 83, 87]])

indx = np.array((windows == np.expand_dims(maxvals, axis = (2, 3)).nonzero())

它为 windows 数组中的四个轴中的每一个返回一个数组。现在我们对每个窗口中的相对索引位置使用一些数学来获取原始数组中出现最大值的索引:

np.sum(indx.reshape(2, 2, -1), axis = 0)
# array([[0, 0, 1, 1, 2, 1, 1, 1, 1, 2, 4, 4, 4, 2],
#        [1, 1, 4, 4, 5, 1, 1, 4, 4, 5, 1, 1, 4, 5]])

进行 reshape 是为了便于添加索引。前两个数组给出窗口位置。后两个数组是相对于窗口的位置。所以我们只需将它们相加即可。 您可以检查第二个轴上的每对值是否是您需要的索引对。

关于python - 如何获取数组滑动窗口 View 中最大元素的矩阵位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72741431/

相关文章:

python - 如何忽略使用自签名证书使用 pip install 到私有(private) pypi 服务器时引发的安全警告

python - Python 样条曲线(使用控制节点和端点)

python - 如果该列大于所述日期,如何绕过此错误以使该列为零? "TypeError: invalid type promotion "

c - 如何使用标准 C/C++ "UNIX timers"为滑动窗口数据传输协议(protocol)创建一系列数据包超时处理程序

python - 采用滑动窗口 Python 生成器函数来随机播放窗口

python - PyPa setup.py 测试脚本

python - 绘制被数据中断的虚线(类似于等高线图)

python - 使用 ADT 方法转换程序 python

python - 如何检查形状文件多边形包含纬度和经度点的 numpy meshgrid

c# - 响应式(Reactive)扩展是否支持滚动缓冲区?