如何通过3X3检索每个部分? [英] how to retrieve every section by 3X3?

查看:68
本文介绍了如何通过3X3检索每个部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何从此数组中检索节:

any one know how to retrieve section from this array:

a=[[1, 3, 2, 5, 7, 9, 4, 6, 8],
  [4, 9, 8, 2, 6, 1, 3, 7, 5],
  [7, 5, 6, 3, 8, 4, 2, 1, 9],
  [6, 4, 3, 1, 5, 8, 7, 9, 2],
  [5, 2, 1, 7, 9, 3, 8, 4, 6],
  [9, 8, 7, 4, 2, 6, 5, 3, 1],
  [2, 1, 4, 9, 3, 5, 6, 8, 7],
  [3, 6, 5, 8, 1, 7, 9, 2, 4],
  [8, 7, 9, 6, 4, 2, 1, 5, 3]]

我的意思是我想检索第3X3节,例如,左上角是:

I mean that i would like to retrieve section 3X3 ,for example,the top left one is:

[[1,3,2],
 [4,9,8],
 [7,5,6]]

需要检索的部分是:

[[0:3,0:3]],[[3:6,0:3]],[[6:9,0:3]]

中间部分

[[0:3,3:6]],[[3:6,3:6]],[[6:9,3:6]]

右侧部分

[[0:3,6:9]],[[3:6,6:9]],[[6:9,6:9]]

如何检索所有这些部分? 有必要使用numpy吗?

How to retrieve all these sections? Is it necessary to use numpy?

推荐答案

这是使用reshaping和置换尺寸的矢量化方法-

Here's a vectorized approach using reshaping and permuting dimensions -

a.reshape(3,3,3,3).transpose(2,0,1,3).reshape(9,3,3)

样品运行-

In [197]: a
Out[197]: 
array([[1, 3, 2, 5, 7, 9, 4, 6, 8],
       [4, 9, 8, 2, 6, 1, 3, 7, 5],
       [7, 5, 6, 3, 8, 4, 2, 1, 9],
       [6, 4, 3, 1, 5, 8, 7, 9, 2],
       [5, 2, 1, 7, 9, 3, 8, 4, 6],
       [9, 8, 7, 4, 2, 6, 5, 3, 1],
       [2, 1, 4, 9, 3, 5, 6, 8, 7],
       [3, 6, 5, 8, 1, 7, 9, 2, 4],
       [8, 7, 9, 6, 4, 2, 1, 5, 3]])

In [198]: a.reshape(3,3,3,3).transpose(2,0,1,3).reshape(9,3,3)
Out[198]: 
array([[[1, 3, 2],
        [4, 9, 8],
        [7, 5, 6]],

       [[6, 4, 3],
        [5, 2, 1],
        [9, 8, 7]],

       [[2, 1, 4],
        [3, 6, 5],
        [8, 7, 9]], ....

如果您需要展平每个这样的部分/窗口,只需调整最后一次重塑,就像这样-

If you need to flatten each such section/window, just tweak the last reshaping, like so -

In [199]: a.reshape(3,3,3,3).transpose(2,0,1,3).reshape(9,9)
Out[199]: 
array([[1, 3, 2, 4, 9, 8, 7, 5, 6],
       [6, 4, 3, 5, 2, 1, 9, 8, 7],
       [2, 1, 4, 3, 6, 5, 8, 7, 9],
       [5, 7, 9, 2, 6, 1, 3, 8, 4],
       [1, 5, 8, 7, 9, 3, 4, 2, 6],
       [9, 3, 5, 8, 1, 7, 6, 4, 2],
       [4, 6, 8, 3, 7, 5, 2, 1, 9],
       [7, 9, 2, 8, 4, 6, 5, 3, 1],
       [6, 8, 7, 9, 2, 4, 1, 5, 3]])

这篇关于如何通过3X3检索每个部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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