Matplotlib rotate image file by X degrees

后端 未结 4 1138
野的像风
野的像风 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:38

    It seems matplotlib has moved on since this question was asked, and it can now natively support affine transformations of images without the user needing to fall back to low-level image manipulation routines.

    This is now documented in the form of an example in https://matplotlib.org/gallery/images_contours_and_fields/affine_image.html.

    Essentially, this requires specifying the appropriate transform keyword argument. The code provided in the original question would be updated as follows:

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

提交回复
热议问题