Skip to main content
 首页 » 编程设计

python之Numpy:旋转 M 的子矩阵 m

2024年10月17日9fff_TT

如果我知道每个方阵子矩阵 m (2x2) 的维度,并且大方阵 M 的维度可以被维度 m 整除:M 模 m == 0。

是否有一种有效的方法可以在以下矩阵 M 内旋转子矩阵:

M = array([[ 1.,  2.,  1.,  2.], 
           [ 3.,  4.,  3.,  4.], 
           [ 1.,  2.,  1.,  2.], 
           [ 3.,  4.,  3.,  4.]]) 

这样的结果是:

M* = array([[ 2.,  4.,  2.,  4.], 
            [ 1.,  3.,  1.,  3.], 
            [ 2.,  4.,  2.,  4.], 
            [ 1.,  3.,  1.,  3.]]) 

特别是,强制使用像 numpy.rot90() 这样的函数会很有用,这样可以实现其他旋转,例如

180: rot90(x, 2) 
270: rot90(x, 3) 

等等

请您参考如下方法:

这是一种使用 reshape 的方法和 transpose -

m,n = M.shape 
out = M.reshape(m//2,2,n//2,2)[...,::-1].transpose(0,3,2,1).reshape(m,n) 

sample 运行-

In [246]: M 
Out[246]:  
array([[51, 70, 59, 38, 84, 18], 
       [80, 25, 76, 43, 80, 48], 
       [92, 98, 46, 14, 65, 47], 
       [73, 31, 32, 79, 87, 70]]) 
 
In [247]: m,n = M.shape 
 
In [248]: M.reshape(m//2,2,n//2,2)[...,::-1].transpose(0,3,2,1).reshape(m,n) 
Out[248]:  
array([[70, 25, 38, 43, 18, 48], 
       [51, 80, 59, 76, 84, 80], 
       [98, 31, 14, 79, 47, 70], 
       [92, 73, 46, 32, 65, 87]]) 

如果你必须使用np.rot90 ,它只适用于前两个轴,我们需要使用 transpose 两次,就像这样 -

rot_arr = np.rot90(M.reshape(m//2,2,n//2,2).transpose(1,3,0,2),1) 
out = rot_arr.transpose(2,0,3,1).reshape(m,n)