(Python) 从较大的 mxm 网格中提取居中的 nxn 网格
对于 Python,有很多关于从较大网格中提取每个可能的 nxn 网格的帖子,但如果我只想从整个 mxm 网格中得到居中 nxn 网格,我就得绕圈子来解决这个问题。
例如:
>>> c = np.random.randint(1,20,size=(9,9))
>>> a
array([[ 8, 9, 4, 1, 3, 10, 14, 13, 2],
[ 7, 3, 1, 14, 4, 11, 19, 5, 14],
[11, 1, 7, 1, 17, 17, 8, 8, 17],
[13, 18, 16, 12, 10, 7, 19, 6, 8],
[15, 2, 13, 15, 1, 1, 2, 5, 15],
[18, 8, 7, 6, 8, 3, 13, 15, 12],
[10, 18, 18, 2, 4, 6, 1, 8, 13],
[ 5, 6, 6, 18, 4, 11, 5, 10, 19],
[15, 14, 13, 6, 19, 17, 17, 16, 1]])
如果我想提取一个 3x3 网格,我会将其置于中间值(此处为 1)的中心,结果将是:
>>> a[3:6,3:6]
array([[12, 10, 7],
[15, 1, 1],
[ 6, 8, 3]])
如果我想要一个以中间值(同样为 1)为中心的 5x5 网格这个更大的 9x9 网格:
>>> a[2:7,2:7]
array([[ 7, 1, 17, 17, 8],
[16, 12, 10, 7, 19],
[13, 15, 1, 1, 2],
[ 7, 6, 8, 3, 13],
[18, 2, 4, 6, 1]])
问题是,如何以编程方式导出值以根据给定的 nxn 大小提取网格?换句话说,对于 3x3 网格,如何得出 3:6,然后对于 5x5 网格如何得出 2:7?我应该注意,nxn 和 mxm 网格将始终是奇数编号,因此存在一个实际中心。
For Python, there are plenty of posts about extracting every possible nxn grid from a larger grid, but if I only want the centered nxn grid from the overall mxm grid, I am running in circles to figure this out.
For example:
>>> c = np.random.randint(1,20,size=(9,9))
>>> a
array([[ 8, 9, 4, 1, 3, 10, 14, 13, 2],
[ 7, 3, 1, 14, 4, 11, 19, 5, 14],
[11, 1, 7, 1, 17, 17, 8, 8, 17],
[13, 18, 16, 12, 10, 7, 19, 6, 8],
[15, 2, 13, 15, 1, 1, 2, 5, 15],
[18, 8, 7, 6, 8, 3, 13, 15, 12],
[10, 18, 18, 2, 4, 6, 1, 8, 13],
[ 5, 6, 6, 18, 4, 11, 5, 10, 19],
[15, 14, 13, 6, 19, 17, 17, 16, 1]])
If I wanted to extract a 3x3 grid, I would center if over the middle value (here, 1), where the resultant would be:
>>> a[3:6,3:6]
array([[12, 10, 7],
[15, 1, 1],
[ 6, 8, 3]])
And if I wanted a 5x5 grid centered on the middle value (again, 1) from this larger 9x9 grid:
>>> a[2:7,2:7]
array([[ 7, 1, 17, 17, 8],
[16, 12, 10, 7, 19],
[13, 15, 1, 1, 2],
[ 7, 6, 8, 3, 13],
[18, 2, 4, 6, 1]])
The problem is, how would one programatically derive the values to extract the grid based on a given nxn size? In other words, for the 3x3 grid, how would one arrive at 3:6, and then 2:7 for the 5x5 grid? I should note, the nxn and mxm grids will always be odd-numbered so there is an actual center.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能适用于这样的事情:
This will probably work with something like this: