numpy滑动二维窗口计算 [英] numpy sliding 2d window calculations

查看:322
本文介绍了numpy滑动二维窗口计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习一种使用numpy的方法来有效解决在各种情况下涉及滑动窗口的问题.这是一个说明我感兴趣的问题类型的示例:

I'm trying to learn a way to use numpy to efficiently solve problems that involve a sliding window in a variety of circumstances. Here is an example illustrating the type of problem I'm interested in:

我有一个很大的2d矩阵,我想对矩阵中每个元素的邻居进行计算.例如,我可能想找到最大值,不包括每个索引在(x-1,y)(x + 1,y + 1)处的索引的negibors的某些特殊值,然后将结果放入另一个不同的2d解决方案"矩阵.

I have a large 2d matrix, and I'd like to perform calculations on neighbors of every element in the matrix. For example, I may want to find the max value, excluding some special value of negibors at indexes at (x-1,y)(x+1,y+1) at each index, and put the result into another different 2d "solution" matrix.

请注意,convolution2d虽然有用,但在这种情况下对我来说不起作用,因为我需要在每个像素上执行特定的操作,而只想在(每个像素的)特定邻居上执行此操作.

Note that convolution2d, while useful won't work for me in this situation because I have specific operations to do at each pixel, and only want to do it on specific neighbors (of every pixel).

另外,奖金将确保我不会超出范围.

Also a bonus would be ensuring I don't go out of bounds.

最后,是否还可以使用任何状态?在所有邻居均为0的情况下,我希望分配一个新的整数id,每次出现时我都会递增.

Finally, is it possible to use any state as well? In cases where all neighbors are 0 I am hoping to assign a new integer id that I increment each time this occurs.

这里是一个例子:

Window:

0 0 1
1 0 0
0 0 0


Input:

0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 9 9 0 0 9 0 0
0 0 0 0 0 0 0 0 0

Output:

0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 1 1 0 0 2 0 0
0 0 0 0 0 0 0 0 0

推荐答案

使用np.roll()创建辅助矩阵.然后在初始矩阵和辅助矩阵之间执行所需的任何操作.例如,取中心单元和两个相邻单元的平均值:

Use np.roll() to create secondary matrices. Then perform whatever operations you need between the initial and secondary matrices. For example, to take the average of the central cell and two neighbors:

sec_a = np.roll(mtrx, -1, axis=0)
sec_b = np.roll(mtrx, -1, axis=1)

result = (mtrx + sec_a + sec_b) / 3

此外,roll()绕边缘滚动,因此无需担心边界.

Additionally, roll() rolls around the edges, so no need to worry about bounds.

这篇关于numpy滑动二维窗口计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆