Python 调整矩阵大小的特殊方法

Python 调整矩阵大小的特殊方法,python,matrix,resize,Python,Matrix,Resize,具有仅填充0和1的nxn(下例中为6x6)矩阵: old_matrix=[[0,0,0,1,1,0], [1,1,1,1,0,0], [0,0,1,0,0,0], [1,0,0,0,0,1], [0,1,1,1,1,0], [1,0,0,1,1,0]] 我想以一种特殊的方式调整它的大小。获取(2x2)子矩阵并检查是否有更多的1或0。这意味着新矩阵将为(3x3),如果子矩阵中的

具有仅填充0和1的nxn(下例中为6x6)矩阵:

old_matrix=[[0,0,0,1,1,0],
            [1,1,1,1,0,0],
            [0,0,1,0,0,0],
            [1,0,0,0,0,1],
            [0,1,1,1,1,0],
            [1,0,0,1,1,0]]
我想以一种特殊的方式调整它的大小。获取(2x2)子矩阵并检查是否有更多的1或0。这意味着新矩阵将为(3x3),如果子矩阵中的值大于0,则将在新矩阵中分配1值。否则,(如果值小于或等于)其新值将为0

new_matrix=[[0,1,0],
            [0,0,0],
            [0,1,0]]
我试着用很多时间来达到这个目的。然而,它似乎不起作用。以下是我目前得到的信息:

 def convert_track(a):

   #converts original map to a 8x8 tile Track

   NEW_TRACK=[]
   w=0 #matrix width
   h=0 #matrix heigth
   t_w=0 #submatrix width
   t_h=0 #submatrix heigth
   BLACK=0 #number of ones in submatrix
   WHITE=0 #number of zeros in submatrix
   while h<=6:
       while w<=6:
           l=[]
           while t_h<=2 and h<=6:
               t_w=0
               while t_w<=2 and w<=6:
                   if a[h][w]==1:
                       BLACK+=1
                   else:
                       WHITE+=1
                   t_w+=1
                   w+=1
                   h+=1
                   t_h+=1
               t_w=0
               t_h+=1
           if BLACK<=WHITE:
               l.append(0)
           else:
               l.append(1)
           BLACK=0
           WHITE=0
           t_h=0     
       NEW_TRACK.append(l)
   return NEW_TRACK 

有没有更简单的方法来实现这一点?我做错了什么

如果你愿意/能够使用NumPy,你可以这样做。如果您正在处理与您所展示的数据类似的任何内容,那么花时间学习是非常值得的,因为这样的操作可以非常高效地完成,并且只需很少的代码

import numpy as np
from scipy.signal import convolve2d

old_matrix=[[0,0,0,1,1,0],
            [1,1,1,1,0,0],
            [0,0,1,0,0,0],
            [1,0,0,0,0,1],
            [0,1,1,1,1,0],
            [1,0,0,1,1,0]]

a = np.array(old_matrix)
k = np.ones((2,2))

# compute sums at each submatrix
local_sums = convolve2d(a, k, mode='valid')

# restrict to sums corresponding to non-overlapping
# sub-matrices with local_sums[::2, ::2] and check if
# there are more 1 than 0 elements
result = local_sums[::2, ::2] > 2

# convert back to Python list if needed
new_matrix = result.astype(np.int).tolist()
结果:

>>> result.astype(np.int).tolist()
[[0, 1, 0], [0, 0, 0], [0, 1, 0]]

这里我使用了
convalve2d
来计算每个子矩阵的和。据我所知,你只对不重叠的子矩阵感兴趣,因此部分
局部_和[::2,::2]
只切掉与之对应的和。

有效的子矩阵将是第一个列表或行的前两个元素,第二个列表或行的前两个元素:[[0,0],[1,1]]真是个不错的解决方案。那么Numpy值得为这种操作学习吗?当然可以。或Matlab/倍频程。但在其他条件相同的情况下(即,您不必使用现有的Matlab代码),NumPy是最好的学习工具。
>>> result.astype(np.int).tolist()
[[0, 1, 0], [0, 0, 0], [0, 1, 0]]