简体   繁体   中英

How to rotate square numpy array of 2 dimensional by 45 degree in python?

I have a numpy array of images. The dimension is 2 and the shape is (100,100). I want to augment more data as I have only 52 set of numpy array. I want to rotate the given array by 45 degree. What should I do for that??

Suppose the array be like

a=[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

Please rotate the given array by 45 degree.

You can use scipy.ndimage.rotate

import numpy as np
from scipy.ndimage import rotate
x = np.arange(25).reshape(5, -1)
rotate(x, angle=45)

Output

array([[ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  6,  0,  0,  0],
       [ 0,  0,  4,  9, 14,  0,  0],
       [ 0,  3,  8, 12, 16, 21,  0],
       [ 0,  0, 10, 15, 20,  0,  0],
       [ 0,  0,  0, 18,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0]])

Not sure if ndimage is in general a good solution for such matrixes. It might work for 45 degrees, but not for other angles without issues. In the example below the "20" gets changed to 0. (Numpy version 1.18.2, scipy 1.4.1)

import numpy as np
from scipy.ndimage import rotate
x = np.arange(25).reshape(5, -1)*1.0
rotate(x, angle=180,reshape=True)
Out[14]: 
array([[24., 23., 22., 21.,  0.],
       [19., 18., 17., 16., 15.],
       [14., 13., 12., 11., 10.],
       [ 9.,  8.,  7.,  6.,  5.],
       [ 4.,  3.,  2.,  1.,  0.]])

x
Out[15]: 
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.],
       [10., 11., 12., 13., 14.],
       [15., 16., 17., 18., 19.],
       [20., 21., 22., 23., 24.]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM