numpy:旋转M的子矩阵m [英] Numpy: rotate sub matrix m of M

查看:123
本文介绍了numpy:旋转M的子矩阵m的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我知道每个方形子矩阵m(2x2)的尺寸,并且大方形矩阵M的尺寸可被尺寸m整除:M模m ==0.

If I knew the dimensions of each square submatrix m (2x2), and that the dimensionality of a large square matrix M was evenly divisible by the dimensionality m: M modulo m == 0.

是否存在一种有效的方法来旋转以下矩阵M中的子矩阵:

Is there an efficient way to rotate submatrices within the following matrix 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()之类的函数,这样可以实现其他旋转,例如

In particular, it would be useful to force the use a function like numpy.rot90(), such that other rotations can be achieved e.g.

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

推荐答案

以下是使用 reshape transpose -

Here's an approach using reshape and transpose -

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

样品运行-

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,例如-

If you have to use np.rot90, which works only on the first two axes, we need to use transpose twice, like so -

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)

这篇关于numpy:旋转M的子矩阵m的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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