Matplotlib rotate image file by X degrees

后端 未结 4 1144
野的像风
野的像风 2020-12-19 06:19

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\

4条回答
  •  渐次进展
    2020-12-19 06:47

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

提交回复
热议问题