将切片环绕在numpy中的2D数组的边缘 [英] Wrap slice around edges of a 2D array in numpy

查看:73
本文介绍了将切片环绕在numpy中的2D数组的边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在Python中使用numpy,并且我有一个任意大小的二维数组.为了方便起见,假设我有一个5 x 5的阵列.具体数字对我的问题不是特别重要;他们只是一个例子.

Suppose I am working with numpy in Python and I have a two-dimensional array of arbitrary size. For convenience, let's say I have a 5 x 5 array. The specific numbers are not particularly important to my question; they're just an example.

a = numpy.arrange(25).reshape(5,5)

这将产生:

[[0, 1, 2, 3, 4 ],
 [5, 6, 7, 8, 9 ],
 [10,11,12,13,14],
 [15,16,17,18,19],
 [20,21,22,23,24]]

现在,假设我要拍摄此数组的2D切片.在正常情况下,这将很容易.要使单元格紧邻2,2,我只需使用a[1:4,1,4]即可产生预期的结果

Now, let's say I wanted to take a 2D slice of this array. In normal conditions, this would be easy. To get the cells immediately adjacent to 2,2 I would simply use a[1:4,1,4] which would yield the expected

[[6, 7,   8 ],
 [11, 12, 13],
 [16, 17, 18]]

但是,如果我想把一片包裹起来怎么办 围绕阵列的边缘?例如,a[-1:2,-1:2]将产生:

But what if I want to take a slice that wraps around the edges of the array? For example a[-1:2,-1:2] would yield:

[24, 20, 21],
[4, 0,  1 ],
[9, 5,  6 ] 

这在边缘无关紧要的几种情况下很有用,例如环绕屏幕的游戏图形.我意识到这可以通过许多if语句和边界检查来完成,但是我想知道是否存在一种更干净,更惯用的方式来完成此操作.

This would be useful in several situations where the edges don't matter, for example game graphics that wrap around a screen. I realize this can be done with a lot of if statements and bounds-checking, but I was wondering if there was a cleaner, more idiomatic way to accomplish this.

环顾四周,我发现了以下几个答案: https://stackoverflow .com/questions/17739543/wrapping-around-slices-in-python-numpy 适用于一维数组,但我还没有弄清楚如何将此逻辑应用于2D切片.

Looking around, I have found several answers such as this: https://stackoverflow.com/questions/17739543/wrapping-around-slices-in-python-numpy that work for 1-dimensional arrays, but I have yet to figure out how to apply this logic to a 2D slice.

从本质上讲,问题是:如何获取numpy中环绕数组边缘的2D数组的2D切片?

So essentially, the question is: how do I take a 2D slice of a 2D array in numpy that wraps around the edges of the array?

在此先感谢任何可以提供帮助的人.

Thank you in advance to anyone who can help.

推荐答案

这将适用于numpy> = 1.7.

This will work with numpy >= 1.7.

a = np.arange(25).reshape(5,5)

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

pad例程有一个'wrap'方法...

The pad routine has a 'wrap' method...

b = np.pad(a, 1, mode='wrap')

array([[24, 20, 21, 22, 23, 24, 20],
       [ 4,  0,  1,  2,  3,  4,  0],
       [ 9,  5,  6,  7,  8,  9,  5],
       [14, 10, 11, 12, 13, 14, 10],
       [19, 15, 16, 17, 18, 19, 15],
       [24, 20, 21, 22, 23, 24, 20],
       [ 4,  0,  1,  2,  3,  4,  0]])

根据情况,您可能必须在任何切片的每一项中加1,以解决b周围的填充问题.

Depending on the situation you may have to add 1 to each term of any slice in order to account for the padding around b.

这篇关于将切片环绕在numpy中的2D数组的边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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