【问题标题】:Matplotlib rotate image file by X degreesMatplotlib 将图像文件旋转 X 度
【发布时间】:2015-07-14 08:40:47
【问题描述】:

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

【问题讨论】:

    标签: python image matplotlib


    【解决方案1】:

    另一种选择可能是使用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()
    
    

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

    【讨论】:

      【解决方案2】:

      自从提出这个问题以来,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()
      

      【讨论】:

        【解决方案3】:

        您可以使用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 并将旋转后的图像blitting 到屏幕上来以某种性能旋转图像(感谢底层的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()
        

        【讨论】:

        • 这给了我奇怪的轮廓线,我正在使用 alpha png 图像。此外,这非常慢(在具有 360 个值的循环中)需要 90 秒。我需要多次旋转这张图片。
        • 您想为旋转的图像制作动画吗?从您的问题中,我刚刚了解到您想旋转然后将其展示给用户。在这种情况下,matplotlib 可能不是执行此操作的正确库,您最好使用基于 SDL 的Pygame(查看pygame.transform.rotate),并且应该在旋转等动画方面提供更好的性能.
        • 我正在制作的程序正在显示我通过 gps 获得的有关车辆的一系列信息(速度、轨迹……),包括我想要显示的方位(角度)顶部角落的小型汽车图像,其行为类似于指南针。我曾想过使用 pygame,但它没有 matplotlib 处理动态数据的大部分简洁功能。
        【解决方案4】:

        您可以使用我在此处找到的以下代码:

        How can I rotate a matplotlib plot through 90 degrees?

        import matplotlib.pyplot as plt
        import scipy
        
        img = scipy.misc.lena()
        tr = scipy.ndimage.rotate(img, 45)
        plt.imshow(tr)
        

        【讨论】:

        • 小心:lena() 已在 0.17 版本中删除
        【解决方案5】:

        我发现以下解决方案非常直观。它使用 Pillow 库来读取图像,然后,我们可以使用内置的旋转函数来旋转图像。图像以逆时针方式旋转并存储在新变量中。最后,我们可以使用 matplotlib 来创建和显示绘图。

        from PIL import Image
        import matplotlib.pyplot as plt
        
        im = Image.open(path-to-file)
        im = im.rotate(90) # Rotates counter clock-wise.
        implot = plt.imshow(im)
        plt.show()
        

        【讨论】:

        • 您好,欢迎来到 SO!虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读tourHow do I write a good answer?
        猜你喜欢
        • 2015-07-04
        • 2018-07-30
        • 2014-07-05
        • 2014-04-27
        • 2012-12-20
        • 2013-10-10
        • 1970-01-01
        • 1970-01-01
        • 2012-02-20
        相关资源
        最近更新 更多