Scipy: image rotation - tiagopereira/python_tips GitHub Wiki

You have an image and want to rotate it by an arbitrary amount of degrees. Scipy has a powerful module, ndimage that does that. (ndimage comes from Numarray, predecessor of numpy, and is also available as numpy.numarray.nd_image -- however, it is not clear how long it will stay there.) However, ndimage has a horrible documentation, and the docstrings only describe a small fraction of the functionalities. Imagine you have an image in the 2D array im.

from scipy import ndimage

im_rot = ndimage.rotate(im,10,mode='constant',cval=100)

The second argument of rotate is the angle in degrees. We can see the results of the rotation with matplotlib's imshow:

imshow(im,interpolation='nearest')
figure()
imshow(im_rot,interpolation='nearest')

image before rotation rotated image

You will notice that the output array is actually larger than the initial one, to accommodate all points. By default rotate uses cubic interpolation, and mode defines how pixels outside the original array are treated. In this case, I used 'constant', so they are given the constant value specified in cval. To see other options for mode check the docstring of ndimage.map_coordinates. This rotate function is very powerful, and it also allows arbitrary rotation of n-D arrays along a plane.