Saving an imshow-like image while preserving resolution

前端 未结 1 1979
一向
一向 2020-12-29 04:41

I have an (n, m) array that I\'ve been visualizing with matplotlib.pyplot.imshow. I\'d like to save this data in some type of raster graphics file (e.g. a png)

相关标签:
1条回答
  • 2020-12-29 05:27

    As you already guessed there is no need to create a figure. You basically need three steps. Normalize your data, apply the colormap, save the image. matplotlib provides all the necessary functionality:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # some data (512x512)
    import scipy.misc
    data = scipy.misc.lena()
    
    # a colormap and a normalization instance
    cmap = plt.cm.jet
    norm = plt.Normalize(vmin=data.min(), vmax=data.max())
    
    # map the normalized data to colors
    # image is now RGBA (512x512x4) 
    image = cmap(norm(data))
    
    # save the image
    plt.imsave('test.png', image)
    

    While the code above explains the single steps, you can also let imsave do all three steps (similar to imshow):

    plt.imsave('test.png', data, cmap=cmap)
    

    Result (test.png):

    enter image description here

    0 讨论(0)
提交回复
热议问题