如何旋转图像文件并在matplotlib中绘制?
我知道我可以使用PIL打开它并旋转它,但这对于这个简单的功能似乎太过分了,我可能没找到。
我在这里发现了这段代码,但似乎不起作用:
from matplotlib import pyplot, image, transforms
img = image.imread('filename.png')
pyplot.ion()
fig = pyplot.figure()
ax = fig.add_subplot(111)
for degree in range(360):
pyplot.clf()
tr = transforms.Affine2D().rotate_deg(degree)
ax.imshow(img, transform=tr)
fig.canvas.draw()
你可以使用rotate
的scipy.ndimage
:
import scipy.misc
from scipy import ndimage
import matplotlib.pyplot as plt
img = scipy.misc.lena()
# img = scipy.misc.face() # lena is not included in scipy 0.19.1
plt.figure(figsize=(12, 2))
for degree in range(5):
plt.subplot(151+degree)
rotated_img = ndimage.rotate(img, degree*60)
plt.imshow(rotated_img, cmap=plt.cm.gray)
plt.axis('off')
plt.show()
这会使图像围绕中心旋转(请参阅docs)。
编辑:
我想要一些动画(我不知道你将如何使用旋转图像,所以我只能推测),也许你最好使用某种游戏/图形库,例如Pygame。在这里,您可以通过使用pygame.transform.rotate
旋转图像并具有一些性能(感谢底层SDL),并将旋转图像旋转到屏幕上。
试试这个(使用图片lena.jpg)来获得平滑旋转的图像:
import pygame
pygame.init()
screen = pygame.display.set_mode([400, 400])
pygame.display.set_caption('Rotating image example')
clock = pygame.time.Clock()
img = pygame.image.load('lena.jpg').convert()
img_rect = img.get_rect(center = screen.get_rect().center)
degree = 0
while degree < 360:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# rotate image
rot_img = pygame.transform.rotate(img, degree)
img_rect = rot_img.get_rect(center = img_rect.center)
# copy image to screen
screen.fill((0, 0, 0))
screen.blit(rot_img, img_rect)
pygame.display.flip()
clock.tick(60)
degree += 1
pygame.quit()
自问这个问题以来,matplotlib似乎已经开始了,它现在可以原生支持图像的仿射变换,而无需用户回退到低级图像处理程序。
现在以https://matplotlib.org/gallery/images_contours_and_fields/affine_image.html中的示例形式记录。
实质上,这需要指定适当的transform关键字参数。原始问题中提供的代码将更新如下:
import matplotlib.pyplot as plt
from matplotlib import transforms
img = plt.imread('filename.png')
fig = plt.figure()
ax = fig.add_subplot(111)
tr = transforms.Affine2D().rotate_deg(rotation_in_degrees)
ax.imshow(img, transform=tr + ax.transData)
plt.show()
你可以使用下面的代码,我在这里找到:
How can I rotate a matplotlib plot through 90 degrees?
from matplotlib import pyplot, image
import scipy
img = scipy.misc.lena()
tr = scipy.ndimage.rotate(img,45)
imshow(tr)