Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

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

Writer Sophia Terry

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.

2

2 Answers

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]])
4

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.]])

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy