Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python save matplotlib figure on an PIL Image object

HI, is it possible that I created a image from matplotlib and I save it on an image object I created from PIL? Sounds very hard? Who can help me?

like image 864
user469652 Avatar asked Oct 15 '10 00:10

user469652


People also ask

How do I save a matplotlib figure in Python?

Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.

How do I save matplotlib figures as SVG?

To save the file in SVG format, use savefig() method where image name is myImagePDF. svg, format="svg". To show the image, use plt. show() method.

How do I save a plot as a JPEG in Python?

To save plot figure as JPG or PNG file, call savefig() function on matplotlib. pyplot object. Pass the file name along with extension, as string argument, to savefig() function.


2 Answers

To render Matplotlib images in a webpage in the Django Framework:

  • create the matplotlib plot

  • save it as a png file

  • store this image in a string buffer (using PIL)

  • pass this buffer to Django's HttpResponse (set mime type image/png)

  • which returns a response object (the rendered plot in this case).

In other words, all of these steps should be placed in a Django view function, in 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')
like image 156
doug Avatar answered Oct 06 '22 14:10

doug


I was having the same question and I stumbled upon this answer. Just wanted to add to the above answer that PIL.Image.fromstring has been deprecated and frombytes should be used now instead of fromstring. Hence, we should modify line:

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

to

pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(), 
                 canvas.tostring_rgb())
like image 25
harshit Avatar answered Oct 06 '22 13:10

harshit