Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate an image in Matplotlib

I'm trying to plot a 2D image in Matplotlib (imported from a png) and rotate it by arbitrary angles. I want to create a simple animation showing the rotation of an object over time, but for now I'm just trying to rotate the image. I've tried several variations on the following code with no success:

import matplotlib.pyplot as plt
import matplotlib.transforms as tr
import matplotlib.cbook as cbook

image_file = cbook.get_sample_data('ada.png')
image = plt.imread(image_file)

imAx = plt.imshow(image)
rot = tr.Affine2D().rotate_deg(30)
imAx.set_transform(imAx.get_transform()+rot)

plt.axis('off') # clear x- and y-axes
plt.show()

I'm sure I'm missing something, but I haven't been able to figure it out from the matplotlib docs and examples.

Thanks!

like image 846
user2844064 Avatar asked Oct 03 '13 19:10

user2844064


People also ask

How do you rotate an image in python?

rotate() function is used to rotate an image by an angle in Python.

How do I rotate an image 90 degrees in python?

You can rotate an image by 90 degrees in counter clockwise direction by providing the angle=90. We also give expand=True, so that the rotated image adjusts to the size of output.

How do I rotate an image 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.


1 Answers

Take a look at this code:

import scipy
from scipy import ndimage
import matplotlib.pyplot as plt
import numpy as np

lena = scipy.misc.lena()
lx, ly = lena.shape
# Copping
crop_lena = lena[lx/4:-lx/4, ly/4:-ly/4]
# up <-> down flip
flip_ud_lena = np.flipud(lena)
# rotation
rotate_lena = ndimage.rotate(lena, 45)
rotate_lena_noreshape = ndimage.rotate(lena, 45, reshape=False)

plt.figure(figsize=(12.5, 2.5))


plt.subplot(151)
plt.imshow(lena, cmap=plt.cm.gray)
plt.axis('off')
plt.subplot(152)
plt.imshow(crop_lena, cmap=plt.cm.gray)
plt.axis('off')
plt.subplot(153)
plt.imshow(flip_ud_lena, cmap=plt.cm.gray)
plt.axis('off')
plt.subplot(154)
plt.imshow(rotate_lena, cmap=plt.cm.gray)
plt.axis('off')
plt.subplot(155)
plt.imshow(rotate_lena_noreshape, cmap=plt.cm.gray)
plt.axis('off')

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0,
                    right=1)

plt.show()
like image 143
Igonato Avatar answered Sep 25 '22 10:09

Igonato