Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate numpy 2D array

I have a set of greyscale images as a 2D numpy arrays.

I need to rotate the images about one point (inside them) of different, float angles. The rotation doesn't need to be in place, and I will allow (of course, if I explained well so far) for interpolation.

I'd like to remain in numpy, as I need to perform numerical operations on the result, but I can also (if that's impossible) allow for step in/out; for example I tried using PIL, namely Image.rotate(theta) but don't understand how to apply that to my arrays, and how to get an array back.

Thank you for your input.

like image 845
astabada Avatar asked Nov 10 '11 17:11

astabada


People also ask

How do you rotate a 2D NumPy array in Python?

NumPy: rot90() function The rot90() function is used to rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis. Array of two or more dimensions. Number of times the array is rotated by 90 degrees.

How do I rotate in NumPy?

Rotate image with NumPy: np. The NumPy function that rotates ndarray is np. rot90() . Specify the original ndarray as the first argument and the number of times to rotate 90 degrees as the second argument.

How do I rotate a NumPy array 180 degrees?

rot90) Using numpy. rot90() , you can rotate the NumPy array ndarray by 90/180/270 degrees.


2 Answers

See the comment of cgohlke Nov 10 '11 at 18:34:

Consider scipy.ndimage.interpolation.shift() and rotate() for interpolated translations and rotations of 2D numpy arrays.

like image 200
Vasco Avatar answered Sep 22 '22 18:09

Vasco


The basic operations are described in the Wikipedia transformation matrix page - I'm not going to try to do ascii matrix art here, but the output P' = R*P where P' is the output point, R is the 2x2 transformation matrix containing sine and cosine of the rotation angle, and P is the input point. If you want to rotate about something other than the origin, then shift the the origin prior to rotation: P' = T + R*(P-T) where T is the translation coordinate. The basic matrix operations don't do interpolation, so if you aren't using a numpy-based image processing library, you'll want to do a reverse transform: for each (integer-valued) output coordinate, find the (floating point) coordinate of the point that would be rotated into it, and interpolate the value of that input point from the surrounding pixels.

like image 36
Dave Avatar answered Sep 21 '22 18:09

Dave