Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

python - Matplotlib rotate image file by X degrees

How can I rotate an image file and plot it in matplotlib?

I know I can open it using PIL and rotate it, but this seems way too much for this simple function, that I'm probably not finding.

I found this piece of code around here, but doesn't seems to work:

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use rotate from 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()

This rotates the image around the center (see docs).

lena

Edit:

I you want some kind of animation (I don't how you're going to use the rotating image, so I can only speculate), maybe you're better off using some kind of game/graphics library, e.g. Pygame. Here you can rotate an image with some performance (thanks to the underlying SDL) by using pygame.transform.rotate and blitting that rotated image onto the screen.

Try this (using a picture lena.jpg) to get a smoothly rotating image:

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...