how to save a pylab figure into in-memory file which can be read into PIL image?

前端 未结 2 1816
情话喂你
情话喂你 2020-11-29 18:45

new to PIL, but want to get a quick solution out of it. The following is my first shot which never works:

import cStringIO
import pylab
from PIL import Image         


        
相关标签:
2条回答
  • 2020-11-29 19:02

    I like having it encapsulated in a function:

    def fig2img(fig):
        """Convert a Matplotlib figure to a PIL Image and return it"""
        import io
        buf = io.BytesIO()
        fig.savefig(buf)
        buf.seek(0)
        img = Image.open(buf)
        return img
    
    

    Then I can call it easily this way:

    import numpy as np
    import matplotlib.pyplot as plt
    from PIL import Image
    
    x = np.arange(-3,3)
    plt.plot(x)
    fig = plt.gcf()
    
    img = fig2img(fig)
    
    img.show()
    
    
    0 讨论(0)
  • 2020-11-29 19:18

    Remember to call buf.seek(0) so Image.open(buf) starts reading from the beginning of the buf:

    import io
    from PIL import Image
    import matplotlib.pyplot as plt
    
    plt.figure()
    plt.plot([1, 2])
    plt.title("test")
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    im = Image.open(buf)
    im.show()
    buf.close()
    
    0 讨论(0)
提交回复
热议问题