90 Degree Rotation for NumPy Multidimensional Array

I have an array with a lot of digits (7.4, 100, 100), which means that I have 7 images 100x100 in size with a depth of 4. I want to rotate these images at an angle of 90 degrees. I tried:

rotated= numpy.rot90(array, 1)

but it changes the shape of the array to (4,7,100,100), which is undesirable. Any solution for this?

+4
source share
2 answers

One solution that doesn’t use np.rot90for clockwise rotation would be to swap the last two axes, and then flip the last one -

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

To rotate counterclockwise, rotate the second last axis -

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

With np.rot90counterclockwise rotation will be -

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 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.dot swapping axes , , , , Scipy rotate.

+1

scipy.ndimage.rotate, , , 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 here enter image description here

(Beware )

, , , Scipy . , . , , , .

. .

+2

Source: https://habr.com/ru/post/1676721/