Matplotlib将图像文件旋转X度

f.r*_*ues 4 python image matplotlib

如何旋转图像文件并在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()
Run Code Online (Sandbox Code Playgroud)

pel*_*son 12

自从提出这个问题以来,似乎 matplotlib 已经有了进展,现在它可以原生支持图像的仿射变换,而无需用户退回到低级图像处理例程。

这现在以https://matplotlib.org/gallery/images_contours_and_fields/affine_image.html中的示例形式记录。

本质上,这需要指定适当的转换关键字参数。原始问题中提供的代码将更新如下:

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()
Run Code Online (Sandbox Code Playgroud)


adr*_*nus 11

你可以使用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()
Run Code Online (Sandbox Code Playgroud)

这会使图像围绕中心旋转(请参阅文档).

莉娜

编辑:

我想要一些动画(我不知道你将如何使用旋转图像,所以我只能推测),也许你最好使用某种游戏/图形库,例如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()
Run Code Online (Sandbox Code Playgroud)


Abh*_*hek 5

另一种选择可能是使用numpyrot90函数。这个想法是将图像转换为 numpy 数组,然后将数组旋转所需的次数。这是一个例子:

import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import numpy as np

with cbook.get_sample_data('ada.png') as image_file:
    image = plt.imread(image_file)
image_arr = np.array(image)

#plt.show() To view the image

for _ in range(3):#3 to turn the image 90 degrees three times = 270 degrees
    image_arr = np.rot90(image_arr)

plt.imshow(image_arr, aspect="auto", extent=(-14,-4,-2,40), zorder = 2, interpolation="nearest")

plt.show()

Run Code Online (Sandbox Code Playgroud)

然而,这仅限于将图像旋转直角(90 的倍数)。