【问题标题】:Python save matplotlib figure on an PIL Image objectPython 将 matplotlib 图保存在 PIL Image 对象上
【发布时间】:2010-10-15 00:45:33
【问题描述】:

嗨,我是否可以从 matplotlib 创建图像并将其保存在从 PIL 创建的图像对象上?听起来很难吗?谁能帮帮我?

【问题讨论】:

    标签: python image matplotlib python-imaging-library


    【解决方案1】:

    在 Django 框架的网页中渲染 Matplotlib 图像:

    • 创建 matplotlib 图

    • 将其保存为 png 文件

    • 将此图像存储在字符串缓冲区中(使用 PIL)

    • 将此缓冲区传递给 Django 的 HttpResponse(设置 mime 类型 image/png)

    • 返回一个响应对象(在本例中为渲染图)。

    换句话说,所有这些步骤都应该放在一个 Django view 函数中,在 views.py 中:

    from matplotlib import pyplot as PLT
    import numpy as NP
    import StringIO
    import PIL
    from django.http import HttpResponse 
    
    
    def display_image(request) :
        # next 5 lines just create a matplotlib plot
        t = NP.arange(-1., 1., 100)
        s = NP.sin(NP.pi * x)
        fig = PLT.figure()
        ax1 = fig.add_subplot(111)
        ax1.plot(t, s, 'b.')
    
        buffer = StringIO.StringIO()
        canvas = PLT.get_current_fig_manager().canvas
        canvas.draw()
        pil_image = PIL.Image.frombytes(
            'RGB', canvas.get_width_height(), canvas.tostring_rgb())
        pil_image.save(buffer, 'PNG')
        PLT.close()
        # Django's HttpResponse reads the buffer and extracts the image
        return HttpResponse(buffer.getvalue(), mimetype='image/png')
    

    【讨论】:

      【解决方案2】:

      我有同样的问题,我偶然发现了这个答案。只是想在上面的答案中补充一点,PIL.Image.fromstring 已被弃用,现在应该使用 frombytes 而不是 fromstring。因此,我们应该修改行:

      pil_image = PIL.Image.fromstring('RGB', canvas.get_width_height(), 
                       canvas.tostring_rgb())
      

      pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(), 
                       canvas.tostring_rgb())
      

      【讨论】:

        猜你喜欢
        • 2019-12-10
        • 2020-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-11
        • 2020-02-17
        • 2015-07-31
        • 2019-07-14
        相关资源
        最近更新 更多