为多维NumPy数组旋转图像90度

2024-05-16 15:48:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个numpy形状数组(7410000100),这意味着我有7张100x100的图像,深度为4。我想把这些图像旋转90度。 我试过:

rotated= numpy.rot90(array, 1)

但它将数组的形状改为(4710100),这是不需要的。有什么解决办法吗?


Tags: 图像numpy数组array形状rotated解决办法rot90
2条回答

不使用np.rot90顺时针旋转的一种解决方案是交换最后两个轴,然后翻转最后一个轴-

img.swapaxes(-2,-1)[...,::-1]

对于逆时针旋转,翻转第二个最后轴-

img.swapaxes(-2,-1)[...,::-1,:]

对于np.rot90,逆时针旋转将是-

np.rot90(img,axes=(-2,-1))

样本运行-

In [39]: img = np.random.randint(0,255,(7,4,3,5))

In [40]: out_CW = img.swapaxes(-2,-1)[...,::-1] # Clockwise

In [41]: out_CCW = img.swapaxes(-2,-1)[...,::-1,:] # Counter-Clockwise

In [42]: img[0,0,:,:]
Out[42]: 
array([[142, 181, 141,  81,  42],
       [  1, 126, 145, 242, 118],
       [112, 115, 128,   0, 151]])

In [43]: out_CW[0,0,:,:]
Out[43]: 
array([[112,   1, 142],
       [115, 126, 181],
       [128, 145, 141],
       [  0, 242,  81],
       [151, 118,  42]])

In [44]: out_CCW[0,0,:,:]
Out[44]: 
array([[ 42, 118, 151],
       [ 81, 242,   0],
       [141, 145, 128],
       [181, 126, 115],
       [142,   1, 112]])

运行时测试

In [41]: img = np.random.randint(0,255,(800,600))

# @Manel Fornos's Scipy based rotate func
In [42]: %timeit rotate(img, 90)
10 loops, best of 3: 60.8 ms per loop

In [43]: %timeit np.rot90(img,axes=(-2,-1))
100000 loops, best of 3: 4.19 µs per loop

In [44]: %timeit img.swapaxes(-2,-1)[...,::-1,:]
1000000 loops, best of 3: 480 ns per loop

因此,对于旋转90度或其倍数,基于numpy.dotswapping axes的旋转在性能上看起来非常好,而且更重要的是,不执行任何插值,否则将更改值,如Scipy的基于旋转的函数所做的那样。

另一种选择

你可以使用^{},我认为它比numpy.rot90更有用

例如

from scipy.ndimage import rotate
from scipy.misc import imread, imshow

img = imread('raven.jpg')

rotate_img = rotate(img, 90)

imshow(rotate_img)

enter image description hereenter image description here

更新(注意插值)

如果你注意旋转的图像,你会看到左边的黑色边框,这是因为Scipy使用插值。所以,实际上图像已经改变了。但是,如果这对您是一个问题,有许多选项可以删除黑边框。

看这个post

相关问题 更多 >